Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS UIButton with UITextAlignmentLeft still centering text?

Problem:
After setting a button's titleEdgeInset and UITextAlignmentLeft the button's title is still centered, not left-aligned.

Details:
I have a button 200px wide using a custom background with an image on the left. Since I don't want the button title to cover the image, I inset the title using titleEdgeInset=UIEdgeInsetsMake(0.0, 45.0, 0.0, 0.0);. This should make title label's x position start at 45px and end at 200px. I also want the button's title to be left-aligned to the image, so I also set textAlignment = UITextAlignmentLeft. However, the title text is still centered between 45px and 200px, not left aligned.

Why?

Here's the relevant code:

button.titleEdgeInsets = UIEdgeInsetsMake(0.0, 45.0, 0.0, 0.0);
button.titleLabel.textAlignment = UITextAlignmentLeft;
[button setTitle:@"X"];
like image 353
memmons Avatar asked Feb 17 '12 19:02

memmons


3 Answers

My test code:

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(20, 20, 200, 72);
UIImage *image = [UIImage imageNamed:@"rob.png"];
[button setImage:image forState:UIControlStateNormal];
button.imageEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
[button setTitle:@"Hello" forState:UIControlStateNormal];
button.titleEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0);
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
[self.view addSubview:button];

Note that I set button.contentHorizontalAlignment, not button.titleLabel.textAlignment. My result:

Screen shot of label

like image 169
rob mayoff Avatar answered Nov 10 '22 04:11

rob mayoff


set contentHorizontalAlignment property for button, it will work.

YourButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

Swift 4.0

YourButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.center
like image 22
Vineesh TP Avatar answered Nov 10 '22 03:11

Vineesh TP


Put a background color on the titleLabel. I'm betting it's being sized to fit, so the text alignment won't matter. It's only as long as it needs to be. What you need to fix is the position of the label itself. You might have to extend the UIButton and override layoutSubviews to get it right. I've never seen a button with anything but a centered label.

like image 4
ZaBlanc Avatar answered Nov 10 '22 03:11

ZaBlanc