1.VFL(Visual Format Language)
let viewsDictionary = ["label1": label1, "label2": label2, "label3": label3, "label4": label4, "label5": label5]
for label in viewsDictionary.keys {
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[\(label)]-|", options: [], metrics: nil, views: viewsDictionary))
}
let metrics = ["labelHeight":88]
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[label1(labelHeight@999)]-[label2(label1)]-[label3(label1)]-[label4(label1)]-[label5(label1)]-(>=10)-|", options: [], metrics: metrics, views: viewsDictionary))
先定义一个字典,将要布局的对象和他的字符串对应起来,因为在 VisualFormat这个参数中是要用字符串来表示控件的。
@数字, 代表这个约束的优先级,默认是1000,代表必须按照这个约束规定的来。[label1(labelHeight@999)]说明label的高度为labelHeight,优先级为999,比1000小,后面的4个标签的高度都按照label1的高度和优先级来,这样一来,就相当于5个标签在他们的父视图的垂直方向是等分父视图的高度的。
2.Ancher
在ios9.0以后,新增加了这几个属性
extension UIView {
/* Constraint creation conveniences. See NSLayoutAnchor.h for details.
*/
open var leadingAnchor: NSLayoutXAxisAnchor { get }
open var trailingAnchor: NSLayoutXAxisAnchor { get }
open var leftAnchor: NSLayoutXAxisAnchor { get }
open var rightAnchor: NSLayoutXAxisAnchor { get }
open var topAnchor: NSLayoutYAxisAnchor { get }
open var bottomAnchor: NSLayoutYAxisAnchor { get }
open var widthAnchor: NSLayoutDimension { get }
open var heightAnchor: NSLayoutDimension { get }
open var centerXAnchor: NSLayoutXAxisAnchor { get }
open var centerYAnchor: NSLayoutYAxisAnchor { get }
open var firstBaselineAnchor: NSLayoutYAxisAnchor { get }
open var lastBaselineAnchor: NSLayoutYAxisAnchor { get }
}
可以利用这些属性来布局和约束控件。
var previous: UILabel!
for label in [label1, label2, label3, label4, label5] {
label.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
label.heightAnchor.constraint(equalToConstant: 88).isActive = true
if previous != nil {
label.topAnchor.constraint(equalTo: previous.bottomAnchor).isActive = true
}
previous = label
}
网友评论