在视图控制器的宽度上水平均匀分布 UIButton 的最简单方法?

Simplest way to evenly distribute UIButtons horizontally across width of view controller?(在视图控制器的宽度上水平均匀分布 UIButton 的最简单方法?)
本文介绍了在视图控制器的宽度上水平均匀分布 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 的最简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
iOS VoiceOver functionality changes with Bundle Identifier(IOS画外音功能随捆绑包标识符而变化)
tabbar middle tab out of tabbar corner(选项卡栏中间的选项卡角外)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)
Get an event when UIBarButtonItem menu is displayed(显示UIBarButtonItem菜单时获取事件)