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"];
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:
set contentHorizontalAlignment property for button, it will work.
YourButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
Swift 4.0
YourButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.center
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With