2013-08-29 150 views
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]; 
} 

任何帮助,这将不胜感激。另外,在此先感谢。

enter image description here

+1

“我有常量'kScreenWidth'和'kScreenHeight'设置屏幕尺寸。”这是一件坏事。你应该问屏幕的尺寸。 iOS开发者已经看到他们的屏幕尺寸假设被破坏了两次(一次iPad出来时,再次出现iPhone 5时)。不排除#3。 –

+0

这是基本自动布局的完美用例。 – uchuugaka

回答

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到你想要的值。

+0

这是一个很棒的答案。非常感谢你! – imns

+0

不客气! – CodenameLambda1