代码实现AutoLayout

纵然Xib在Xcode5下可以很好帮助我们快速搭建页面,但是避免不了团队工作中所带来的冲突,这使得Xib搭建页面是个麻烦事,所以在团队开发中避免不了写代码来构建页面,而AutoLayout是IOS6以后的主流页面构建方式。那如何使用代码来实现AutoLayout?其实也不难,NSLayoutConstraint和VFL足以解决这些难题。

NSLayoutConstraint

在使用NSLayoutConstraint之前,需要了解它几个基本属性:

NSLayoutAttributeBaseline 基线
NSLayoutAttributeBottom 底部
NSLayoutAttributeCenterX X轴中点
NSLayoutAttributeCenterY Y轴中点
NSLayoutAttributeLeading 头
NSLayoutAttributeLeft 左
NSLayoutAttributeRight 右
NSLayoutAttributeTop 顶部
NSLayoutAttributeTrailing 尾
NSLayoutAttributeWidth 宽
NSLayoutAttributeHeight 高
NSLayoutAttributeNotAnAttribute 0 没属性


约束条件:

NSLayoutRelationLessThanOrEqual -1 小于或等于
NSLayoutRelationEqual 0 等于
NSLayoutRelationGreaterThanOrEqual 1 大于或等于

这几个属性和约束条件是我们代码构建AutoLayout的约束(NSLayoutConstraint)经常需要使用到的,NSLayoutConstraint有一个静态方法去构建约束:

Create constraints explicitly. Constraints are of the form “view1.attr1 = view2.attr2 * multiplier + constant” .If your equation does not have a second view and attribute, use nil and NSLayoutAttributeNotAnAttribute.

1
+(id)constraintWithItem:(id)view1 attribute:(NSLayoutAttribute)attr1 relatedBy:(NSLayoutRelation)relation toItem:(id)view2 attribute:(NSLayoutAttribute)attr2 multiplier:(CGFloat)multiplier constant:(CGFloat)c;

约束条件的添加需要遵循以下几个方面

1、自身的约束添加到自身View上
2、对于两个同层级view之间的约束关系,添加到他们的父view上
3、对于两个不同层级view之间的约束关系,添加到他们最近的共同父view上
4、对于有层次关系的两个view之间的约束关系,添加到层次较高的父view上

Single Demo