41

Now I want to alignment the text of button to the left with code , how to do ? and I code this :

button.titleLabel.textAlignment = UITextAlignmentLeft;

but it doesn't work.

AsTeR
  • 7,247
  • 14
  • 60
  • 99
jin
  • 2,145
  • 5
  • 27
  • 44

5 Answers5

80

You have to use contentVerticalAlignment and contentHorizontalAlignment of the button.

AlexVogel
  • 10,601
  • 10
  • 61
  • 71
  • 1
    and I use it: button.contentVerticalAlignment = button.contentHorizontalAlignment = UIControlContentVerticalAlignmentLeft; but it doesn't work,how to use this property? – jin Nov 12 '10 at 09:14
  • 5
    OK,I found that:button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill; Thank you! – jin Nov 15 '10 at 01:39
  • 1
    Refer this [answer](http://stackoverflow.com/a/2765158/49186). you will change the contentEdgeInsets property as well – dexter Apr 19 '12 at 17:44
  • Do you know what .titleLabel.textAlignment is for, then? – emmics Jun 19 '17 at 21:23
25

Use ContentHorizontalAlignment as below

btnObj.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
hii
  • 255
  • 4
  • 18
AP_
  • 1,013
  • 12
  • 13
9

Swift Code

button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left
Metalhead1247
  • 1,978
  • 1
  • 17
  • 28
2

For those who are using Swift 3

button.contentHorizontalAlignment = .left

Above code align text to left border, so you might want little padding.

button.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0)
Aamir
  • 16,329
  • 10
  • 59
  • 65
0

Setting to button titleLable alignment also works perfectly.

btn.titleLabel.textAlignment=NSTextAlignmentCenter;
Aamir
  • 16,329
  • 10
  • 59
  • 65
John
  • 238
  • 2
  • 11