简体   繁体   English

将一组按钮放在屏幕中央

[英]center a group of buttons on the screen

I'm creating an iphone app and I need to center a variable (1 to 3) number of buttons on the screen. 我正在创建一个iPhone应用程序,需要在屏幕上居中放置可变(1到3)个按钮。 I'd like each button to have a margin of 20.0f between them, and not have them spaced out equally. 我希望每个按钮之间都留有20.0f的余量,而不希望它们之间的间距相等。 I made a pretty picture below to demonstrate what I'm talking about. 我在下面做了一张漂亮的照片来演示我在说什么。

I'm having the hardest time getting this to work. 我最困难的是让它工作。

Things of note: 注意事项:

int btnWidth = 50;
int margin = 20;

I have constants kScreenWidth and kScreenHeight setup for the screen dimensions. 我为屏幕尺寸设置了常数kScreenWidthkScreenHeight

I'm creating the buttons like normal inside a loop, but the math for the x position of each button is eluding me. 我正在循环内像正常创建按钮一样,但是每个按钮的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];
}

Any help with this would be greatly appreciated. 任何帮助,将不胜感激。 Also, thanks in advance. 另外,在此先感谢。

在此处输入图片说明

Lets say you need three buttons in center, then following is the process to achieve the x coordinate of each of 3 buttons. 假设您需要在中心放置三个按钮,接下来是实现三个按钮中每个按钮的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);
}

In the above, you can change the values of numOfButtons, buttonSize and maxSeparationBwButtons to your desired values. 在上面,您可以将numOfButtons,buttonSize和maxSeparationBwButtons的值更改为所需的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM