I\'ve looked through many answers and they all seem very complex! Most recently I was looking at this answer although I\'d prefer not to have to put my buttons inside views.
I know this question is a bit old, but I've been programming in iOS for a few years now and dislike using autolayout. So I wrote a helper method to evenly space UIButtons horizontally and center them vertically within a UIView. This works great for menu bars.
- (void) evenlySpaceTheseButtonsInThisView : (NSArray *) buttonArray : (UIView *) thisView {
int widthOfAllButtons = 0;
for (int i = 0; i < buttonArray.count; i++) {
UIButton *thisButton = [buttonArray objectAtIndex:i];
[thisButton setCenter:CGPointMake(0, thisView.frame.size.height / 2.0)];
widthOfAllButtons = widthOfAllButtons + thisButton.frame.size.width;
}
int spaceBetweenButtons = (thisView.frame.size.width - widthOfAllButtons) / (buttonArray.count + 1);
UIButton *lastButton = nil;
for (int i = 0; i < buttonArray.count; i++) {
UIButton *thisButton = [buttonArray objectAtIndex:i];
if (lastButton == nil) {
[thisButton setFrame:CGRectMake(spaceBetweenButtons, thisButton.frame.origin.y, thisButton.frame.size.width, thisButton.frame.size.height)];
} else {
[thisButton setFrame:CGRectMake(spaceBetweenButtons + lastButton.frame.origin.x + lastButton.frame.size.width, thisButton.frame.origin.y, thisButton.frame.size.width, thisButton.frame.size.height)];
}
lastButton = thisButton;
}
}
Just copy and paste this method into any view controller. Then to access it, I first created all the buttons I wanted, then called the method with all of the buttons in an array, along with the UIView I wanted it in.
[self evenlySpaceTheseButtonsInThisView:@[menuButton, hierarchyMenuButton, downButton, upButton] :menuView];
The advantage of this method is that you don't need autolayout and it's super easy to implement. The disadvantage is that if your app works in landscape and portrait, you will need to make sure to call this method again after the view has been rotated.