在视图控制器的宽度上水平均匀分布 UIButton 的最简单方法? [英] Simplest way to evenly distribute UIButtons horizontally across width of view controller?

查看:21
本文介绍了在视图控制器的宽度上水平均匀分布 UIButton 的最简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查看了很多答案,它们看起来都非常复杂!最近我在看 this answer 虽然我不希望将按钮放在视图中.

I've looked through many answers and they all seem very complex! Most recently I was looking at this answer although I'd prefer not to have to put my buttons inside views.

我有 6 个尺寸相同的 UIButton.我想在我的根视图控制器的整个宽度和底部均匀地水平放置它们.

I have 6 UIButtons that are all the same dimensions. I want to space them evenly horizontally across the full width and at the bottom of my root view controller.

|                                      |
|                                      |
|  [b1]  [b2]  [b3]  [b4]  [b5]  [b6]  |
________________________________________

以编程方式实现这一目标的最简单方法是什么?

What is the simplest way to achieve this programmatically?

推荐答案

我认为这比接受答案上的链接更简单.好的,首先让我们创建一些按钮:

I think this is simpler than the link on the accepted answer. Ok, firstly lets create some buttons:

UIButton *button1 = [UIButton buttonWithType:UIButtonTypeSystem];
button1.translatesAutoresizingMaskIntoConstraints = NO;
[button1 setTitle:@"Btn1" forState:UIControlStateNormal];

...为 6 个按钮执行 6 次,但是你喜欢然后将它们添加到视图中:

... do that 6 times for 6 buttons, however you like then add them to the view:

[self.view addSubview:button1];
[self.view addSubview:button2];
[self.view addSubview:button3];
[self.view addSubview:button4];
[self.view addSubview:button5];
[self.view addSubview:button6];

将一个按钮固定到视图底部:

Fix one button to the bottom of your view:

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:button1 attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1 constant:0]];

然后告诉所有按钮宽度相等,并在宽度上均匀分布:

Then tell all the buttons to be equal width and spread out equally across the width:

NSDictionary *views = NSDictionaryOfVariableBindings(button1, button2, button3, button4, button5, button6);
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[button1][button2(==button1)][button3(==button1)][button4(==button1)][button5(==button1)][button6(==button1)]|" options:NSLayoutFormatAlignAllBottom metrics:nil views:views]];

结果:

这篇关于在视图控制器的宽度上水平均匀分布 UIButton 的最简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆