手写的约束的几种方式
- Using NSLayoutConstraint initializer
- Using Visual Format Language
- Using UIView.AutoresizingMask
- Using NSLayoutAnchor
- intrinsicContentSize and NSLayoutAnchor
自己常用的就是第4种,其中有两种写法
parentView.addConstraints()
newView.translatesAutoresizingMaskIntoConstraints = false let horizontalConstraint = newView.centerXAnchor.constraint(equalTo: view.centerXAnchor) let verticalConstraint = newView.centerYAnchor.constraint(equalTo: view.centerYAnchor) let widthConstraint = newView.widthAnchor.constraint(equalToConstant: 100) let heightConstraint = newView.heightAnchor.constraint(equalToConstant: 100) view.addConstraints([horizontalConstraint, verticalConstraint, widthConstraint, heightConstraint])
|
NSLayoutConstraint.activate()
newView.translatesAutoresizingMaskIntoConstraints = false let horizontalConstraint = newView.centerXAnchor.constraint(equalTo: view.centerXAnchor) let verticalConstraint = newView.centerYAnchor.constraint(equalTo: view.centerYAnchor) let widthConstraint = newView.widthAnchor.constraint(equalToConstant: 100) let heightConstraint = newView.heightAnchor.constraint(equalToConstant: 100) NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint, widthConstraint, heightConstraint])
|
参考
How to add constraints programmatically using Swift