首页 > 代码库 > AutoLayout的实现

AutoLayout的实现

第一步:

_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];

 

AutoLayout的实现