代碼實現Auto Layout的步驟:
1>利用NSLayoutConstraint類創建具體的約束對象
2>添加約束對象到相應的view上
-(void)addConstraint:(NSLayoutConstraint *)constraint;
-(void)addConstraints:(NSArray *)constraints;
注1:代碼實現Auto Layout的注意要先禁止autoresizing功能,設置view的下面屬性為NO
view.translatesAutoresizingMaskIntoConstraints= NO;
注2:添加約束之前,一定要保證相關控件都已經在各自的父控件上
注3:不用再給view設置frame
一個NSLayoutConstraint對象就代表一個約束
創建約束對象的常用方法
+(id)constraintWithItem:(id)view1attribute:(NSLayoutAttribute)attr1 relatedBy:(NSLayoutRelation)relationtoItem:(id)view2 attribute:(NSLayoutAttribute)attr2multiplier:(CGFloat)multiplier constant:(CGFloat)c;
view1:要約束的控件
attr1:約束的類型(做怎樣的約束)
relation:與參照控件之間的關系
view2:參照的控件
attr2:約束的類型(做怎樣的約束)
multiplier:乘數
c:常量
注:自動布局有個核心公式
obj1.property1 =(obj2.property2 * multiplier)+ constant value
如讓一個View居中顯示代碼實現如下
// 1.添加控件 UIView *blueView = [[UIView alloc] init]; blueView.backgroundColor = [UIColor blueColor]; [self.view addSubview:blueView]; // 2.添加約束 // 關閉autoresizing blueView.translatesAutoresizingMaskIntoConstraints = NO; /** 寬高:100 位置:在父控件中居中 */ // blueView的width == 100 NSLayoutConstraint *width = [NSLayoutConstraint constraintWithItem:blueView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:100]; [blueView addConstraint:width]; // blueView的height == 100 NSLayoutConstraint *height = [NSLayoutConstraint constraintWithItem:blueView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:100]; [blueView addConstraint:height]; // blueView的CenterX == self.view的CenterX * 1.0 + 0.0 NSLayoutConstraint *centerX = [NSLayoutConstraint constraintWithItem:blueView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0]; [self.view addConstraint:centerX]; // blueView的CenterY == self.view的CenterY * 1.0 + 0.0 NSLayoutConstraint *centerY = [NSLayoutConstraint constraintWithItem:blueView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0]; [self.view addConstraint:centerY];
3.1 UILabel使用Auto Layout
3.2 使用Auto Layout制作動畫
在修改了約束之後,只要執行下面代碼,就能做動畫效果
[UIViewanimateWithDuration:1.0 animations:^{
[添加了約束的viewlayoutIfNeeded];
}];
@interface ViewController () @property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftMargin; @property (weak, nonatomic) IBOutlet NSLayoutConstraint *width; @property (weak, nonatomic) IBOutlet UIView *redView; @end @implementation ViewController - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { self.leftMargin.constant = 100; self.width.constant = 200; [UIView animateWithDuration:2.0 animations:^{ [self.view layoutIfNeeded]; [self.redView layoutIfNeeded]; }]; } @end