IOS 代碼添加約束

項(xiàng)目中頁面代碼布局使用的一般都是Masonry,修改以前的項(xiàng)目是發(fā)現(xiàn)有的頁面是用OC原生的NSLayoutConstraint進(jìn)行布局。做個(gè)記錄,以后忘了可以瞄一眼~

1.如果是通過代碼添加Autolayout, 那么必須在添加約束之前禁用Autoresizing
2.禁用Autoresizing時(shí), 必須是給誰添加就禁用誰的, 也就是說如果禁用了父控件無效
3.添加約束之前, 必須保證被約束的控件已經(jīng)添加到父控件中了
self.view.translatesAutoresizingMaskIntoConstraints = NO;

Item == 第一個(gè)控件
attribute == 第一個(gè)控件的什么屬性
relatedBy == 等于/小于等于/大于等于
toItem == 第二個(gè)控件
attribute == 第二個(gè)控件的什么屬性
multiplier == 乘以多少
constant == 加上多少

NSLayoutConstraint *topCos = [NSLayoutConstraint constraintWithItem:messageView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:20];
[self.view addConstraint:topCos];

給view添加寬度

NSLayoutConstraint *topCos = [NSLayoutConstraint constraintWithItem:messageView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeWidth multiplier:1.0 constant:100];
[self.view addConstraint:topCos];

如此就可了。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容