Sunday, October 9, 2016

Adding a Visual Format Language Constraint

The code adds a vertical and horizontal constraint to a UIView that is already on the storyboard.
 
@IBOutlet weak var myView: UIView!

override func viewDidLoad() {
    super.viewDidLoad()

    myView.translatesAutoresizingMaskIntoConstraints = false
    
    let views = ["myView" : myView!]
    
    let constraints = NSLayoutConstraint.constraints(withVisualFormat: 
        "H:|[myView]|", 
        options: [] , metrics: nil, views: views)
    NSLayoutConstraint.activate(constraints)
    
    let vconstraints = NSLayoutConstraint.constraints(withVisualFormat: 
        "V:|-[myView]-|", 
        options: [] , metrics: nil, views: views)
    NSLayoutConstraint.activate(vconstraints)
}
 

Note: When creating the dictionary (views) it is important to include the exclamation point on the view you are adding. Otherwise you will get an error such as "unrecognized selector sent to instance".

See this post for more examples of using the Visual Format Language.

(Xcode 8, Swift 3.0)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

SwiftUI Search & Filter with Combine - Part 3 (iOS, Xcode 13, SwiftUI, 2...

In part 3 of the Searchable video series, I show you how to use Combine in #SwiftUI for the search and filter logic connected to the searcha...