将一组按钮置于屏幕上

时间:2013-08-29 12:57:13

标签: iphone ios objective-c cocoa-touch

我正在创建一个iphone应用程序,我需要在屏幕上设置一个变量(1到3)个按钮。我希望每个按钮在它们之间有20.0f的余量,而不是它们的间距相等。我在下面做了一张漂亮的照片来展示我在说什么。

我正在努力工作。

注意事项:

int btnWidth = 50;
int margin = 20;

我为屏幕尺寸设置了常量kScreenWidthkScreenHeight

我在循环中创建正常的按钮,但是每个按钮的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];
}

对此的任何帮助将不胜感激。另外,提前谢谢。

enter image description here

1 个答案:

答案 0 :(得分:1)

假设你需要在中心有三个按钮,然后是实现3个按钮中每个按钮的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的值更改为所需的值。