Design-By-Intent
You just describe what you want and let Auto Layout figure out how to deliver it.
A = B*m + c
第一步:
_tableView.translatesAutoresizingMaskIntoConstraints = NO;
第二步:生成constraint并添加到superview当中
方式一:
UITableView *tableview = [[UITableView alloc] init]; [superView addSubview:tableview]; NSLayoutConstraint *cn = [NSLayoutConstraint constraintWithItem:tableview attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0]; [superView addConstraint:cn]; cn = [NSLayoutConstraint constraintWithItem:tableview attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-20.0]; [superView addConstraint:cn];
Visual Format
NSDictionary *views = NSDictionaryOfVariableBindings(_tableView);
NSMutableArray *constraints = [NSMutableArray array]; _tableView.translatesAutoresizingMaskIntoConstraints = NO; [constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_tableView]-|" options:0 metrics:nil views:views]]; [constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[_tableView]-|" options:0 metrics:nil views:views]]; [self.view addConstraints:constraints];
在@implementation 区块的上面添加如下代码:
@interface UIWindow (AutoLayoutDebug) +(UIWindow *)keyWindow; -(NSString *)_autolayoutTrace; @end
在需要查看Trace的位置添加如下代码:
NSLog(@"%@", [[UIWindow keyWindow] _autolayoutTrace]);
例如:
- (void)viewDidAppear:(BOOL)animated{ [super viewDidAppear:animated]; NSLog(@"%@", [[UIWindow keyWindow] _autolayoutTrace]); } - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{ [super didRotateFromInterfaceOrientation:fromInterfaceOrientation]; NSLog(@"%@", [[UIWindow keyWindow] _autolayoutTrace]); }
这时会在输出的地方输出Trace信息:
*Between a view and its superview: Add to the superview
*Between two views with the same superview: Add to the superview
*One just the view: Add to the view itself
This method is called when the view first becomes visibile and every time afterwards when the constraints need to change.
在需要更新constraints的时候,调用 [self.view setNeedsUpdateConstraints]会调用UpdateConstraints函数
UIView 会 Call UpdateConstraints
UIKit 会 Call UpdateViewConstraints