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)