NSLayoutAnchor介绍:
NSLayoutAnchor作为iOS9的新特性是对AutoLayout创建约束的补充,核心还是NSLayoutConstraint,可以避免过长创建约束代码。NSLayoutAnchor可以理解为约束描边,通过视图之间的边关系和X、Y轴关系,以及定义自身宽高来创建约束。
由于NSLayoutAnchor是系统自带的,非第三方库,所以代码添加约束前,一定要将View的translatesAutoresizingMaskIntoConstraints属性设置为false,否则约束不起效果。
NSLayoutAnchor布局使用:
view1.translatesAutoresizingMaskIntoConstraints = false
view1.topAnchor.constraint(equalTo: view2.bottomAnchor).isActive = true // view1的顶部挨着view2的底部
view1.topAnchor.constraint(equalTo: view2.bottomAnchor, constant: 30).isActive = true // view1的顶部距离view2的底部30
view1.topAnchor.constraint(greaterThanOrEqualTo: view2.bottomAnchor).isActive = true // view1的顶部距view2的底部挨着或大于0
view1.topAnchor.constraint(greaterThanOrEqualTo: view2.bottomAnchor, constant: 30).isActive = true // view1的顶部距view2的底部挨着或大于30
view1.widthAnchor.constraint(equalToConstant: 100).isActive = true // view1的宽度为100
view1.widthAnchor.constraint(greaterThanOrEqualToConstant: 100).isActive = true // view1的宽度至少为100
view1.widthAnchor.constraint(equalTo: view2.widthAnchor).isActive = true // view1的宽度和view2的宽度一致
view1.widthAnchor.constraint(equalTo: view2.widthAnchor, constant: 20).isActive = true // view1的宽度比view2的宽度多20
view1.centerXAnchor.constraint(equalTo: view2.centerXAnchor).isActive = true // view1的x轴和view2的x轴一致
view1.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true // view1的y轴和view(父视图)的y轴一致
NSLayoutAnchor布局更新:
NSLayoutAnchor的布局更新和使用PurLayout一样,因为每个约束方法都是返回一个NSLayoutConstraint对象。
我们先定义一个对象接受想要更改的某个约束
private var myConstraint: NSLayoutConstraint!
myConstraint = view1.widthAnchor.constraint(equalToConstant: 100)
myConstraint.isActive = true
然后在需要的时候修改就可以了
myConstraint.constant = 200
或者移除旧的约束,重新写新约束
myConstraint.autoRemove()
myConstraint = view1.widthAnchor.constraint(equalToConstant: 300)
myConstraint.isActive = true