iOS UIButton with UITextAlignmentLeft still centering text? iOS UIButton with UITextAlignmentLeft still centering text? ios ios

iOS UIButton with UITextAlignmentLeft still centering text?


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


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.