横向均匀分布三个按钮ios
Posted
技术标签:
【中文标题】横向均匀分布三个按钮ios【英文标题】:Horizontally distribute three buttons evenly ios 【发布时间】:2017-06-03 13:33:07 【问题描述】:我有三个UIButtons
和一个支架UIView
我希望我的所有三个UIButton
在UIView
内垂直居中,并且我希望它们水平分布均匀
float ycentre = CGRectGetMidY(self.buttonHolderView.bounds);
float xposition = (self.buttonHolderView.frame.size.width - 135.0f)/4.0f;
self.button1 = [[UIButton alloc]initWithFrame:CGRectMake(xposition,0, 45, 30)];
self.button1.center = CGPointMake(self.button1.frame.origin.x, ycentre);
self.button2 = [[UIButton alloc]initWithFrame:CGRectMake((xposition*2)+45,0, 45, 30)];
self.button2.center = CGPointMake(self.button2.frame.origin.x, ycentre);
self.button3 = [[UIButton alloc]initWithFrame:CGRectMake((xposition*3)+90,0, 45, 30)];
self.button3.center = CGPointMake(self.button3.frame.origin.x, ycentre);
[self.button3 addTarget:self action:@selector(ShareButtonClicked) forControlEvents:UIControlEventTouchUpInside];
[self.buttonHolderView addSubview:self.button1];
[self.buttonHolderView addSubview:self.button2];
[self.buttonHolderView addSubview:self.button3];
每个按钮都有高度 30 和宽度 45 ,但我的代码没有平均分配它们有什么问题?
【问题讨论】:
发布您正在寻找的用户界面... 【参考方案1】:将它们放在UIStackView
中。它使间隔视图变得非常容易。
【讨论】:
最好的方法。冰雹UIStackView
...! :P
注意UIStackView
需要ios 9.0+【参考方案2】:
如下设置按钮的frame
,不要设置center
float thirdOfWidth = (self.buttonHolderView.frame.width/3.0);
float buttonWidth = 45.0;
float buttonHeight = 30.0;
self.button1 = [[UIButton alloc]initWithFrame:CGRectMake(thirdOfWidth*0 + (thirdOfWidth - buttonWidth)/2, (self.buttonHolderView.frame.height - buttonHeight)/2, 45, 30)];
self.button2 = [[UIButton alloc]initWithFrame:CGRectMake(thirdOfWidth*1 + (thirdOfWidth - buttonWidth)/2, (self.buttonHolderView.frame.height - buttonHeight)/2, 45, 30)];
self.button3 = [[UIButton alloc]initWithFrame:CGRectMake(thirdOfWidth*2 + (thirdOfWidth - buttonWidth)/2, (self.buttonHolderView.frame.height - buttonHeight)/2, 45, 30)];
【讨论】:
【参考方案3】:也可以通过任意数量的按钮循环完成
NSInteger count = 3;
CGFloat buttonWidth = 45;
CGFloat buttonHeight = 30;
CGFloat x = (self.bounds.size.width - buttonWidth) / 2;
CGFloat verticalSpacing = ((self.bounds.size.height - buttonHeight * count) / count) - buttonHeight / 2;
CGFloat y = verticalSpacing;
for (int i = 0; i < count; i++)
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x, y, buttonWidth, buttonHeight)];
[self addSubview:button];
y += buttonHeight + verticalSpacing;
【讨论】:
以上是关于横向均匀分布三个按钮ios的主要内容,如果未能解决你的问题,请参考以下文章
Android开发 - 掌握ConstraintLayout链条(Chains)