NSLayoutConstraint-代碼實現自動佈局的函數用法說明

[NSLayoutConstraint constraintWithItem:(id)item
                             attribute:(NSLayoutAttribute)attribute
                             relatedBy:(NSLayoutRelation)relation
                                toItem:(id)otherItem
                             attribute:(NSLayoutAttribute)otherAttribute
                            multiplier:(CGFloat)multiplier
                              constant:(CGFloat)constant]



參數說明:

第一個參數:指定約束左邊的視圖view1

第二個參數:指定view1的屬性attr1,具體屬性見文末。

第三個參數:指定左右兩邊的視圖的關係relation,具體關係見文末。

第四個參數:指定約束右邊的視圖view2

第五個參數:指定view2的屬性attr2,具體屬性見文末。

第六個參數:指定一個與view2屬性相乘的乘數multiplier

第七個參數:指定一個與view2屬性相加的浮點數constant


這個函數的對照公式爲:

view1.attr1 <relation> view2.attr2 * multiplier + constant


注意:

1.如果你想設置的約束裏不需要第二個view,要將第四個參數設爲nil,第五個參數設爲NSLayoutAttributeNotAnAttribute


舉例:

[NSLayoutConstraint constraintWithItem:view1
                             attribute:NSLayoutAttributeLeft
                             relatedBy:NSLayoutRelationEqual
                                toItem:view2
                             attribute:NSLayoutAttributeRight
                            multiplier:1
                              constant:10]


翻譯過來就是:view1的左側,在,view2的右側,再多10個點,的地方。


附視圖的屬性和關係的值:


typedef NS_ENUM(NSInteger, NSLayoutRelation) {
    NSLayoutRelationLessThanOrEqual = -1,          //小於等於
    NSLayoutRelationEqual = 0,                     //等於
    NSLayoutRelationGreaterThanOrEqual = 1,        //大於等於
};
typedef NS_ENUM(NSInteger, NSLayoutAttribute) {
    NSLayoutAttributeLeft = 1,                     //左側
    NSLayoutAttributeRight,                        //右側
    NSLayoutAttributeTop,                          //上方
    NSLayoutAttributeBottom,                       //下方
    NSLayoutAttributeLeading,                      //首部
    NSLayoutAttributeTrailing,                     //尾部
    NSLayoutAttributeWidth,                        //寬度
    NSLayoutAttributeHeight,                       //高度
    NSLayoutAttributeCenterX,                      //X軸中心
    NSLayoutAttributeCenterY,                      //Y軸中心
    NSLayoutAttributeBaseline,                     //文本底標線
                                                                                                                                                   
    NSLayoutAttributeNotAnAttribute = 0            //沒有屬性
};


NSLayoutAttributeLeft/NSLayoutAttributeRightNSLayoutAttributeLeading/NSLayoutAttributeTrailing的區別是left/right永遠是指左右,而leading/trailing在某些從右至左習慣的地區會變成,leading是右邊,trailing是左邊。(大概是⊙﹏⊙b)



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章