iOS自动布局:等同的空间,以适应Superviews宽度

可能重复:
Autolayout甚至间距

我试图创build一个滚动条与button(类似于UISegmentedControl )。 superview是一个UIScrollView 。 只要button不适合滚动视图,滚动视图应滚动。 到目前为止,几乎一切工作正常:

有很多button(向右滚动):

滚动视图

没有那么多button:

视图不滚动

现在,我的目标是,如果所有button都有空间,它们应该在整个320px视图中均匀分布。 我怎样才能定义button之间的空间约束?

现在,我使用以下约束(self是一个UIScrollView ):

 UIView *firstButton = self.buttons[0]; [self.buttonConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"|-(5)-[firstButton]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(firstButton)]]; UIView *lastButton = [self.buttons lastObject]; [self.buttonConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"[lastButton]-(5)-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(lastButton)]]; UIView *previousView = nil; for (UIView *view in self.buttons) { if (previousView) { [self.buttonConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"[previousView]-(5)-[view]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(previousView, view)]]; } previousView = view; } 

如果我从UIScrollView中将超级视图的types更改为UIView ,我会得到以下结果,但仍然不是我想要的,但是至less它会查找最后一个将其绑定到右边缘的button的约束(有道理,这不会发生的滚动视图,因为内容大小是自动设置):

UIView作为超级视图

有任何想法吗?

 - (void) viewWillLayoutSubviews { // UIButton *button1, *button2, *button3, *button 4 ; // NSMutableArray *constraintsForButtons ; float unusedHorizontalSpace = self.view.bounds.size.width - button1.intrinsicContentSize.width - button2.intrinsicContentSize.width - button3.intrinsicContentSize.width - button4.intrinsicContentSize.width ; NSNumber* spaceBetweenEachButton= [NSNumber numberWithFloat: unusedHorizontalSpace / 5 ] ; [self.view removeConstraints:constraintsForButtons] ; [constraintsForButtons removeAllObjects] ; [constraintsForButtons addObjectsFromArray: [NSLayoutConstraint constraintsWithVisualFormat: @"H:|-(space)-[button1]-(space)-[button2]-(space)-[button3]-(space)-[button4]-(space)-|" options: NSLayoutFormatAlignAllCenterY metrics: @{@"space":spaceBetweenEachButton} views: NSDictionaryOfVariableBindings(button1,button2,button3,button4) ] ] ; [constraintsForButtons addObjectsFromArray: [NSLayoutConstraint constraintsWithVisualFormat: @"V:|[button1]" options: 0 metrics: nil views: NSDictionaryOfVariableBindings(button1) ] ] ; [self.view addConstraints:constraintsForButtons] ; } 

这不像你的漂亮,它假定有4个button,但是它们也是相同的空间。 也就是说,button之间的空白空间都具有相同的宽度。 这并不意味着button1和button2的NSLayoutAttributeLeading之间的距离与button2和button3之间的距离相同。

肖像景观