首页 > 代码库 > Autolayout 约束类方法的理解(学习笔记二)
Autolayout 约束类方法的理解(学习笔记二)
随apple大屏手机的问世,屏幕适配问题被堆到风口浪尖,对于代码画UI的同学无疑是个噩梦。在上班闲暇之余,学习了autolayout;autolayout从iOS6开始使用,因为各种坑,只有一些advanced coder们所用,但现在autolayout今非昔比了。学习的必要性也越发强烈。
autolayout也可以用代码实现,apple可爱的工程师开发了一个可视化语言VFL(Visual Format Language),这里不解释VFL的语法,但是要解释一个约束的类方法,个人觉得这对理解autolayout的约束有重要意义。方法如下
/* 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.
*/
+(instancetype)constraintWithItem:(id)view1 attribute:(NSLayoutAttribute)attr1 relatedBy:(NSLayoutRelation)relation toItem:(id)view2 attribute:(NSLayoutAttribute)attr2 multiplier:(CGFloat)multiplier constant:(CGFloat)c;
参数官方解释
参数一、view1:The view for the left-hand side of the constraint.(view1)
参数二、attr1:The attribute of the view for the left-hand side of the constraint.(view1约束属性NSLayoutAttribute)
参数三、relation:The relationship between the left-hand side of the constraint and the right-hand side of the constraint.(两个view约束关系,==,<=,>=,三种)
参数四、view2:The view for the right-hand side of the constraint.(view2,可以为nil)
参数五、attr2:The attribute of the view for the right-hand side of the constraint.(view2约束属性,view2为nil时此参数要传NSLayoutAttributeNotAnAttribute)
参数六、multiplier:The constant multiplied with the attribute on the right-hand side of the constraint as part of getting the modified attribute.(相当于数学中的斜率,相当于attr1=m*attr2+c,中的斜率k,c则为偏移)
参数七、c:The constant added to the multiplied attribute value on the right-hand side of the constraint to yield the final modified attribute.
咋一看那么多参数和英文好恐怖啊,用谷歌翻译理解了半天就是没明白multiplier与c的意思,通过看外国友人的微博才茅塞顿开。详情请看参数后中文解释,但是看到这里肯定有同学还是不理解attr1=m*attr2+c,那就举几个特例子就好理解了,首先将c=0,attr1与attr2都是NSLayoutAttributeCenterY
,那么m=1时,说明view1.center.y与view2.center.y相等,同理m=1/2,则view1.center.y是view2.center.y的1/2,有同学问,那还有参数c呢,不用急,一个个来;假设m=1且c=10,那么view1.center.y在view2.center.y再往下偏移10像素。理解这个方法那么IB与SB中的约束就很简单啦
Autolayout 约束类方法的理解(学习笔记二)