0

I tried to use:

button.titleLabel?.textAlignment = .left

to left align the text on a button, but the text still appears in the centre. I don't have any code to set the title of the button to the centre of the button so it must do that by default.

Can anyone tell me how to use the textAlignment property on the titleLabel of the button for left alignment?

Edit: To address the proposals to close the question, you can if you see fit to do so, but my question is not the same as simply asking how to left align the text in a button. I asked how to use a specific property (titleLabel) to do so, which I believe has not been asked before. And I received a quality answer which answered my question.

cheznead
  • 2,589
  • 7
  • 29
  • 50
  • 1
    Possible duplicate: https://stackoverflow.com/questions/2765024/how-to-set-the-title-of-uibutton-as-left-alignment?rq=1 – Cyril Sep 30 '17 at 23:22
  • Yea, not a duplicate. Question here is asking specifically about using titleLabel property to left align - I already know how to do it using contentHorizontalAlignment and am not asking how to left align in general. – cheznead Sep 30 '17 at 23:24
  • It is duplicated ;) https://stackoverflow.com/a/32324628/5501940 – Ahmad F Sep 30 '17 at 23:40
  • Possible duplicate of [How to set the title of UIButton as left alignment?](https://stackoverflow.com/questions/2765024/how-to-set-the-title-of-uibutton-as-left-alignment) – Ahmad F Sep 30 '17 at 23:40
  • That isn't the same question either. Please refer me to the same question having been asked before. I am not asking how to set the title to the left. I asked how to use titleLabel to do so, and I received an answer that gave me the required information. – cheznead Sep 30 '17 at 23:48

1 Answers1

1

You cannot really / should not really use the titleLabel property for this since the UIButton decides how to layout the label, where to position it and with what size, etc. If the button decides to put the label in the center and size it to the minimal dimensions it needs to display the text then changing any alignment property of the label will have no effect.

button.contentHorizontalAlignment = .left

is the way to go. Do not change the integrated label, but the button.

luk2302
  • 55,258
  • 23
  • 97
  • 137