Simplest way to evenly distribute UIButtons horizontally across width of view controller?(在视图控制器的宽度上水平均匀分布 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 的最简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在视图控制器的宽度上水平均匀分布 UIButton 的最简单方法?
基础教程推荐
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- iOS4 创建后台定时器 2022-01-01
