當使用xib,并使用了AutoLayout之后,當需要適配機型時,或者手動更改視圖的frame的時候,就需要修改約束啦.其實很簡單的.
1.首先從xib中吧改變的約束拖到view上或者ViewController上
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topLayout;
//機型封裝到單例中 全局都可以使用
if (CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size)) {
return UIScreenSizeType_640x960;
}
else if(CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size)){
return UIScreenSizeType_640x1136;
}else if(CGSizeEqualToSize(CGSizeMake(750, 1334), [[UIScreen mainScreen] currentMode].size)){
return UIScreenSizeType_750x1334;
}else if(CGSizeEqualToSize(CGSizeMake(1242, 2208), [[UIScreen mainScreen] currentMode].size)){
return UIScreenSizeType_1242x2208;
}
return UIScreenSizeType_000x000;}
if([UIScreen currentScreenSizeType] == UIScreenSizeType_640x960){
_topLayout.constant = 40;
}else if([UIScreen currentScreenSizeType] == UIScreenSizeType_640x1136){
_topLayout.constant = 40;
}else if([UIScreen currentScreenSizeType] == UIScreenSizeType_750x1334){
_topLayout.constant = 40;
}else if([UIScreen currentScreenSizeType] == UIScreenSizeType_1242x2208){
_topLayout.constant = 40;
}
2.還可以為控件自定義一個約束
NSLayoutConstraint *myConstraint =[NSLayoutConstraint
constraintWithItem:iSinaButton //子試圖
attribute:NSLayoutAttributeCenterX //子試圖的約束屬性
relatedBy:NSLayoutRelationEqual //屬性間的關系
toItem:self.view//相對于父試圖
attribute:NSLayoutAttributeCenterX//父試圖的約束屬性
multiplier:1.0
constant:0.0];// 固定距離
[self.view addConstraint: myConstraint];//為iSinaButton重新添加一個約束