2

When you add a label to a storyboard in XCode and stretch it the width of the screen, you can get the text for the label to start from the left by selecting the left alignment in the Attributes Inspector, however, that option doesn't exist for buttons. I've stretched a button the full width of the screen but the text starts in the middle and centers by default. Using this SO answer How to make UIButton's text alignment center? Using IB, I found the property NSTextAlignmentLeft and set it like this on a button but when I run the code, the text is still starting from the middle

 [self.answerChoice1 setTitle:string1 forState:UIControlStateNormal];
 [self.answerChoice1.titleLabel setTextAlignment: NSTextAlignmentLeft];

I also tried putting the second of the above lines in the init method of the view with same results.

Community
  • 1
  • 1
BrainLikeADullPencil
  • 11,313
  • 24
  • 78
  • 134

1 Answers1

5

The text is being left-aligned. The problem is that the title label (within which the text is left-aligned) is itself located in the middle of the button!

So, what you want to do is adjust the position of the label within the button. There are various ways to do this. For example, look at the button's contentHorizontalAlignment.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • in apple documentation, it says the default for contentHorizontalAlignment is left. Since the label in my buttons are in the center, I'm not sure that's the right property. Can you explain? https://developer.apple.com/library/ios/documentation/uikit/reference/uicontrol_class/reference/reference.html#//apple_ref/occ/instp/UIControl/contentHorizontalAlignment – BrainLikeADullPencil Apr 20 '14 at 17:12
  • 1
    forget it, it worked `self.answerChoice1.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;`though I'm not sure why it was needed since default is left – BrainLikeADullPencil Apr 20 '14 at 17:13