我让它工作的唯一方法是在边缘和按钮之间放置标签(没有标题,因此它们是不可见的),以便按钮和标签占据屏幕上的所有垂直空间。按钮具有固有大小,但标签没有,因此它们会扩展或收缩以正确填充空间。
-(void)viewDidLoad {
[super viewDidLoad];
NSMutableDictionary *viewsDict = [NSMutableDictionary dictionary];
NSArray *titles = @[@"Button 1",@"Button 2",@"Button 3",@"Button 4",@"Button 5"];
for (int i=1; i<6; i++) {
UIButton *b = [UIButton buttonWithType:1];
[b setTitle:titles[i-1] forState:UIControlStateNormal];
[b setTranslatesAutoresizingMaskIntoConstraints:NO];
[viewsDict setObject:b forKey:[NSString stringWithFormat:@"b%d",i]];
}
for (int i=1; i<7; i++) { // labels for spacing
UILabel *l = [[UILabel alloc ]init];
[l setTranslatesAutoresizingMaskIntoConstraints:NO];
[viewsDict setObject:l forKey:[NSString stringWithFormat:@"l%d",i]];
}
for (id obj in viewsDict.allKeys)
[self.view addSubview:viewsDict[obj]];
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[l1][b1][l2(==l1)][b2][l3(==l1)][b3][l4(==l1)][b4][l5(==l1)][b5][l6(==l1)]|"
options:NSLayoutFormatAlignAllLeading
metrics:nil
views:viewsDict];
NSArray *constraints2 = [NSLayoutConstraint constraintsWithVisualFormat:@"|-100-[b1]"
options:NSLayoutFormatAlignAllLeading
metrics:nil
views:viewsDict];
[self.view addConstraints:constraints];
[self.view addConstraints:constraints2];
}
这将所有按钮从左边缘对齐 100 个点,按钮之间的间距相等。这将调整屏幕大小和旋转。