1

我正在创建一个 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];
}

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

在此处输入图像描述

4

1 回答 1

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 的值更改为您想要的值。

于 2013-08-29T13:10:59.197 回答