iOS Swift Constraint programatically 1
Constraint
Constraint is useful to arrange UI correctly.
In Storyboard or nib(xib), we can see parameters in tool. We can understand easily(visible)
By code, it is difficult to understand immediately, but it can.
Example
This is an example to add view to top layer(Window).
let mainWindow : UIWindow = UIApplication.sharedApplication().keyWindow! let topView : UIView = UIView() topView.backgroundColor = UIColor.orangeColor() mainWindow.addSubview(topView) topView.translatesAutoresizingMaskIntoConstraints = false let singleTap : UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("tapView")) topView.addGestureRecognizer(singleTap) let dic : [String : AnyObject] = ["topView": topView] let height: NSLayoutConstraint = NSLayoutConstraint(item: topView, attribute: NSLayoutAttribute.Height, relatedBy: .Equal, toItem: nil, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 80) mainWindow.addConstraint(height) // Add constaints let c: NSLayoutConstraint = NSLayoutConstraint(item: topView, attribute: .CenterY, relatedBy: .Equal, toItem: mainWindow, attribute: .CenterY, multiplier: 1, constant: 0) mainWindow.addConstraint(c) let verticalConstraint = NSLayoutConstraint.constraintsWithVisualFormat("H:|-10-[topView]-10-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dic) mainWindow.addConstraints(verticalConstraint) mainWindow.layoutIfNeeded()
Constraints should be added to parent view.