iOS自動布局 NSLayoutConstraint基礎(chǔ)

必要的一條:

要使用NSLayoutConstraint必須設(shè)置translatesAutoresizingMaskIntoConstraints為NO;

例:

// 1 : 創(chuàng)建一個黃色的View

UIView *yellowView = [[UIView alloc]init];

yellowView.backgroundColor = [UIColor yellowColor];

// 2 : 注意首先要添加到subView里面

[self.view addSubview:yellowView];

// 3 : 取消黃色View的autoresizing

// YES 代表使用autoresizing 如果食用autolayout需要設(shè)置為NO

yellowView.translatesAutoresizingMaskIntoConstraints = NO;

// 4 : 設(shè)置約束

/**

1).WithItem? 代表的是需要設(shè)置約束的空間(yellowView)

2).attribute 代表的是要做約束的那一條線

NSLayoutAttributeLeft = 1,//左側(cè)

NSLayoutAttributeRight,//右側(cè)

NSLayoutAttributeTop,//上方

NSLayoutAttributeBottom,//下方

NSLayoutAttributeLeading,//首部

NSLayoutAttributeTrailing,//尾部

NSLayoutAttributeWidth,//寬度

NSLayoutAttributeHeight,//高度

NSLayoutAttributeCenterX,//X軸中心

NSLayoutAttributeCenterY,//Y軸中心

NSLayoutAttributeBaseline,//文本底標(biāo)線

NSLayoutAttributeNotAnAttribute = 0//沒有屬性

3).relatedBy 比較的方式 =(NSLayoutRelationEqual) <=(NSLayoutRelationLessThanOrEqual) >=(NSLayoutRelationGreaterThanOrEqual)

4).toItem? ? 代表的是被比較的控件

5).attribute 代表的是被比較的控件的比較的位置

*/

// 4.1 : 設(shè)置距離上方

NSLayoutConstraint *yellowViewTop = [NSLayoutConstraint constraintWithItem:yellowView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1 constant:100];

[self.view addConstraint:yellowViewTop];

// 4.2 : 設(shè)置距離左邊

NSLayoutConstraint *yellowViewLeft = [NSLayoutConstraint constraintWithItem:yellowView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1 constant:100];

[self.view addConstraint:yellowViewLeft];

// 4.3 : 設(shè)置寬度

// 注意:設(shè)置自身的寬高,不需要設(shè)置toItem對象,直接傳入nil

NSLayoutConstraint *yellowWidth = [NSLayoutConstraint constraintWithItem:yellowView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeWidth multiplier:1 constant:100];

// 注意: 約束添加到哪個對象身上

[yellowView addConstraint:yellowWidth];

// 4.4 : 設(shè)置高度

NSLayoutConstraint *yellowHeight = [NSLayoutConstraint constraintWithItem:yellowView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeHeight multiplier:1 constant:100];

[yellowView addConstraint:yellowHeight];

效果如圖:

*建議使用第三方插件Masonry(github即可下載)

*簡化代碼如下

// 1 : 創(chuàng)建一個黃色的View

UIView *yellowView = [[UIView alloc]init];

yellowView.backgroundColor = [UIColor yellowColor];

// 2 : 注意首先要添加到subView里面

[self.view addSubview:yellowView];

// 3 : 設(shè)置約束

[yellowView mas_makeConstraints:^(MASConstraintMaker *make) {

make.top.left.mas_equalTo(100);

make.height.width.mas_equalTo(100);

}];

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

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

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