Autolayout约束类方法的理解(学习笔记二)

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

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中的约束就很简单啦。

相关文档
最新文档