Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I programmatically set the vertical alignment of a UIButton - iOS

Tags:

I know how to set the vertical alignment of a button with IB; see here. But I can not do it programmatically... This is one of the things I have tried:

UIButton *button  = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 110, 130)]; [button setTitle:@"Align" forState:UIControlStateNormal]; button.backgroundColor = [UIColor whiteColor]; button.titleLabel.textColor = [UIColor grayColor]; [button setContentVerticalAlignment:UIControlContentVerticalAlignmentBottom];  [self.view addSubview:button];  [button release]; 

I have also tried insets...

But the alignment won't change.

Please note that I want to keep the CustomStyle of the button (I don't want the default look and feel).

like image 544
lindon fox Avatar asked Dec 14 '11 11:12

lindon fox


People also ask

How do you left align text in UIButton?

Here is the correct solution to add an UILabel to an UIButton to align the button text to better control the button 'title': NSString *myLabelText = @"Hello World"; UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom]; // position in the parent view and set the size of the button myButton.

Which element by default allows vertical-align?

Baseline. The default value of vertical-align (if you declare nothing), is baseline.


2 Answers

You can alignment (horizontal and vertical) the text of button in this way:

        UIButton *button  = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 200, 70)];         button.backgroundColor = [UIColor whiteColor];         button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;         button.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;         [button setTitle:@"Align" forState:UIControlStateNormal];         [self.container addSubview:button]; 
like image 179
Alessandro Pirovano Avatar answered Oct 23 '22 17:10

Alessandro Pirovano


contentVerticalAlignment is the way to go. Could be how you're creating the button. Try this:

 UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];  button.frame = CGRectMake(10, 10, 110, 130);  // rest of your code  // don't release button explicitly 
like image 44
XJones Avatar answered Oct 23 '22 17:10

XJones