我想在 View 中均匀分布四个按钮。在 Storyboard中,我将按钮放置在纵向 View 中,以便间距正确。但我没有找到正确的约束设置来使按钮在任何 View 宽度(对于 iPad 纵向或横向)上均匀分布。因此,我添加了以下代码片段,使用第一个和第四个按钮作为 anchor 将按钮移动到所需位置:
// evenly space the buttons
CGPoint leftPoint = self.button1.center;
CGPoint rightPoint = self.button4.center;
CGFloat width = rightPoint.x - leftPoint.x;
leftPoint.x += width / 3;
rightPoint.x -= width / 3;
self.button2.center = leftPoint;
self.button3.center = rightPoint;
定位代码工作正常,但我的困难是找到进行调整的最佳位置。 - (void)viewDidAppear:(BOOL)动画 似乎是最好的地方。但是,如果我选择不同的 View ,当我返回到该 View 时,按钮将恢复到其初始( Storyboard约束)指定位置。 viewDidAppear 代码将再次被调用,但它无法成功移动按钮。就好像他们的位置在那个时间点被锁定一样。
我想我的主要问题是是否有一种方法可以使用约束来实现我所追求的均匀间距。或者第二个问题是如何覆盖这两个按钮的自动定位。
最佳答案
使用布局约束这是一件相对困难的事情,这取决于您想要什么。我在这里有一个示例,它创建 4 个按钮(在代码中)以及 5 个用作按钮之间的间隔符的标签。按钮的大小由其固有内容大小决定,按钮之间以及按钮与包含 View 的边之间的间距都是相同的。
-(void)viewDidLoad {
[super viewDidLoad];
NSMutableDictionary *viewsDict = [NSMutableDictionary dictionary];
NSArray *titles = @[@"Short",@"Longer",@"Short",@"The Longest"];
for (int i=1; i<5; 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<6; i++) {
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:@"|[l1][b1][l2(==l1)][b2][l3(==l1)][b3][l4(==l1)][b4][l5(==l1)]|"
options:NSLayoutFormatAlignAllBaseline
metrics:nil
views:viewsDict];
NSArray *constraints2 = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[b1]-|"
options:0
metrics:nil
views:viewsDict];
[self.view addConstraints:constraints];
[self.view addConstraints:constraints2];
}
当 View 大小发生变化时,按钮的间距将自动调整,就像旋转一样。
关于ios UIViewController 以编程方式定位按钮不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13598568/