iOS UIButton with UITextAlignmentLeft still centering text?

30,792

Solution 1

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

Solution 2

set contentHorizontalAlignment property for button, it will work.

YourButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

Swift 4.0

YourButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.center

Solution 3

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.

Solution 4

Set contentHorizontalAlignment property for a button:

yourButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

Solution 5

Swift 3

Set contentHorizontalAlignment property do the work. Thanks

yourButton.contentHorizontalAlignment = .left
Share:
30,792
memmons
Author by

memmons

Founder of App Apps, LLC. Creator of Audiotorium Notes for iPad & VideoBot.

Updated on July 13, 2022

Comments

  • memmons
    memmons almost 2 years

    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"];