iphone - 在屏幕上居中放置一组按钮

标签 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

最佳答案

假设您需要居中的三个按钮,那么以下是实现三个按钮中每个按钮的 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/

相关文章:

ios - 如何在字典中设置文本字段的值?

objective-c - 释放属性(property)(Objective-C)

iphone - 如何在 iPhone 上使用 GNU C 编译器/gcc 和移动终端编译简单的 C 文件?

youtube - iPhone、Mobile Safari、YouTube ...留在页面上

iphone - MPMusicPlayerController 速度调节

iphone - iOS:Facebook 发布隐私

ios - Cocos2D reload 白屏报错

iOS 自动布局旋转应用程序崩溃

ios - 本地化字符串中的奇怪字符

objective-c - 捕获所有 Objective-C 消息并获取 Cocoa 运行时中的对象列表