标签:
1. 利用Auto Layout整体排列控件
下面的代码演示了一个控件如何在其父容器中垂直水平居中:
UIView *box = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 200, 150)]; box.backgroundColor = [UIColor grayColor]; [self.view addSubview:box]; UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [button setTitle:@"a button" forState:UIControlStateNormal]; [button sizeToFit]; button.translatesAutoresizingMaskIntoConstraints = NO; [box addSubview:button]; NSMutableArray *array = [[NSMutableArray alloc] init]; [array addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[box]-(<=1)-[button]" options:NSLayoutFormatAlignAllCenterX metrics:nil views:NSDictionaryOfVariableBindings(box,button)]]; [array addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[box]-(<=1)-[button]" options:NSLayoutFormatAlignAllCenterY metrics:nil views:NSDictionaryOfVariableBindings(box,button)]]; [box addConstraints:array];
下面的代码演示了多个控件其父容器中水平左对齐,垂直居中:
UIView *box = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 200, 150)]; box.backgroundColor = [UIColor grayColor]; [self.view addSubview:box]; UILabel *label = [[UILabel alloc] init]; label.text = @"a label"; [label sizeToFit]; label.backgroundColor = [UIColor redColor]; label.translatesAutoresizingMaskIntoConstraints = NO; [box addSubview:label]; UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [button setTitle:@"a button" forState:UIControlStateNormal]; [button sizeToFit]; button.translatesAutoresizingMaskIntoConstraints = NO; [box addSubview:button]; NSMutableArray *array = [[NSMutableArray alloc] init]; [array addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[button]-|" options:NSLayoutFormatAlignAllLeft metrics:nil views:NSDictionaryOfVariableBindings(button)]]; [array addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"|-15-[myLabel]-5-[myButton]" options:NSLayoutFormatAlignAllCenterY metrics:nil views:@{@"myLabel":label, @"myButton":button}]]; [box addConstraints:array];
标签:
原文地址:http://www.cnblogs.com/wayne23/p/4276705.html