我正在创建一个 iPhone 应用程序,我需要在屏幕上居中放置数量可变(1 到 3)的按钮。我希望每个按钮在它们之间有 20.0f 的边距,并且它们之间的间隔不相等。我在下面制作了一张漂亮的图片来展示我在说什么。
我很难让它发挥作用。
注意事项:
int btnWidth = 50;
int margin = 20;
我为屏幕尺寸设置了常量 kScreenWidth
和 kScreenHeight
。
我在一个循环中像平常一样创建按钮,但我无法计算每个按钮的 x 位置。
for (UIButton *btn in _someArray) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
int x = ??????????;
button.frame = CGRectMake( x, (kScreenHeight * 0.75f), 50.0, 30.0);
[self.controller.currentView addSubview:button];
}
如有任何帮助,我们将不胜感激。另外,提前致谢。
最佳答案
假设您需要居中的三个按钮,那么以下是实现三个按钮中每个按钮的 x 坐标的过程。
//Define these globally somewhere
CGSize buttonSize = CGSizeMake(50,50);
int numOfButtons = 3; //num of buttons horizontally in one line. this will be 2 for 2nd and 1 for the third line as per your reference screen.
CGFloat maxSeparationBwButtons = 20.0f; //your horizontal margin b/w buttons
CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
CGFloat totalLengthWithOffsets = buttonSize.width*(CGFloat)numOfButtons+(maxSeparationBwButtons)*((CGFloat)(numOfButtons+1));
CGFloat originatingX = (screenWidth - totalLengthWithOffsets)/2.0f;
//global definition ends...
//Now you can use this method to get the desired button's x coordinate
//Note : in 3 buttons the 1st button starts at position 0 and the last at 2 (aka n-1)
-(CGFloat)getXForButtonAtPosition:(int)position
{
return (originatingX + maxSeparationBwButtons + (buttonSize.width+maxSeparationBwButtons)*(CGFloat)position);
}
在上面,您可以将 numOfButtons、buttonSize 和 maxSeparationBwButtons 的值更改为您想要的值。
关于iphone - 在屏幕上居中放置一组按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18511664/