- 代码
1 - (void)viewDidLoad 2 { 3 [super viewDidLoad]; 4 5 UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 6 [button setTitle:@"哈哈哈" forState:UIControlStateNormal]; 7 [self.view addSubview:button]; 8 9 //1. 关闭autoresize自动翻译 10 button.translatesAutoresizingMaskIntoConstraints = NO; 11 12 //2. 构建约束 13 NSDictionary * map = NSDictionaryOfVariableBindings(button); 14 NSString * format = @"|-10-[button]-10-|"; 15 NSArray * constains1 = 16 [NSLayoutConstraint constraintsWithVisualFormat:format 17 options:0 18 metrics:nil 19 views:map]; 20 //3. 约束加入视图 21 [self.view addConstraints:constains1]; 22 [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-10-[button(==20)]" options:0 metrics:nil views:map]]; 23 24 25 UIButton * button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 26 [button1 setTitle:@"左按钮" forState:UIControlStateNormal]; 27 [self.view addSubview:button1]; 28 29 UIButton * button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 30 [button2 setTitle:@"右按钮" forState:UIControlStateNormal]; 31 [self.view addSubview:button2]; 32 33 //1. 34 button1.translatesAutoresizingMaskIntoConstraints = NO; 35 button2.translatesAutoresizingMaskIntoConstraints = NO; 36 37 //2. 38 39 NSDictionary * views = NSDictionaryOfVariableBindings(button1,button2); 40 NSArray * horizontal = 41 [NSLayoutConstraint constraintsWithVisualFormat: 42 @"|-10-[button1]-10-[button2(==button1)]-10-|" 43 options: 44 NSLayoutFormatAlignAllCenterY 45 metrics:nil 46 views:views]; 47 48 [self.view addConstraints:horizontal]; 49 50 NSArray * bottom = 51 [NSLayoutConstraint constraintsWithVisualFormat: 52 @"V:[button1]-10-|" 53 options:0 54 metrics:nil 55 views:views]; 56 57 [self.view addConstraints:bottom]; 58 59 60 61 }
- IB
在Interface Builder中,右下角的3个按钮用于设置自动布局。