必要的一條:
要使用NSLayoutConstraint必須設置translatesAutoresizingMaskIntoConstraints為NO;
例:
// 1 : 創建一個黃色的View
UIView *yellowView = [[UIView alloc]init];
yellowView.backgroundColor = [UIColor yellowColor];
// 2 : 注意首先要添加到subView里面
[self.view addSubview:yellowView];
// 3 : 取消黃色View的autoresizing
// YES 代表使用autoresizing 如果食用autolayout需要設置為NO
yellowView.translatesAutoresizingMaskIntoConstraints = NO;
// 4 : 設置約束
/**
1).WithItem? 代表的是需要設置約束的空間(yellowView)
2).attribute 代表的是要做約束的那一條線
NSLayoutAttributeLeft = 1,//左側
NSLayoutAttributeRight,//右側
NSLayoutAttributeTop,//上方
NSLayoutAttributeBottom,//下方
NSLayoutAttributeLeading,//首部
NSLayoutAttributeTrailing,//尾部
NSLayoutAttributeWidth,//寬度
NSLayoutAttributeHeight,//高度
NSLayoutAttributeCenterX,//X軸中心
NSLayoutAttributeCenterY,//Y軸中心
NSLayoutAttributeBaseline,//文本底標線
NSLayoutAttributeNotAnAttribute = 0//沒有屬性
3).relatedBy 比較的方式 =(NSLayoutRelationEqual) <=(NSLayoutRelationLessThanOrEqual) >=(NSLayoutRelationGreaterThanOrEqual)
4).toItem? ? 代表的是被比較的控件
5).attribute 代表的是被比較的控件的比較的位置
*/
// 4.1 : 設置距離上方
NSLayoutConstraint *yellowViewTop = [NSLayoutConstraint constraintWithItem:yellowView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1 constant:100];
[self.view addConstraint:yellowViewTop];
// 4.2 : 設置距離左邊
NSLayoutConstraint *yellowViewLeft = [NSLayoutConstraint constraintWithItem:yellowView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1 constant:100];
[self.view addConstraint:yellowViewLeft];
// 4.3 : 設置寬度
// 注意:設置自身的寬高,不需要設置toItem對象,直接傳入nil
NSLayoutConstraint *yellowWidth = [NSLayoutConstraint constraintWithItem:yellowView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeWidth multiplier:1 constant:100];
// 注意: 約束添加到哪個對象身上
[yellowView addConstraint:yellowWidth];
// 4.4 : 設置高度
NSLayoutConstraint *yellowHeight = [NSLayoutConstraint constraintWithItem:yellowView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeHeight multiplier:1 constant:100];
[yellowView addConstraint:yellowHeight];
效果如圖:
*建議使用第三方插件Masonry(github即可下載)
*簡化代碼如下
// 1 : 創建一個黃色的View
UIView *yellowView = [[UIView alloc]init];
yellowView.backgroundColor = [UIColor yellowColor];
// 2 : 注意首先要添加到subView里面
[self.view addSubview:yellowView];
// 3 : 設置約束
[yellowView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.left.mas_equalTo(100);
make.height.width.mas_equalTo(100);
}];