90

I am trying to set the title on a Button to left. But everything i tried is not working.

With:

UILabelButton.titleLabel.textAlignment = .Left

Or:

UILabelButton.contentVerticalAlignment = UIControlContentVerticalAlignment // There is no left

The button title is still centered.

Is there another Property?

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
derdida
  • 14,784
  • 16
  • 90
  • 139

6 Answers6

237

Use contentHorizontalAlignment.You have to use UIControlContentHorizontalAlignment.Left.You need to usehorizontal not vertical.

btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left

Swift 3.x

btn.contentHorizontalAlignment = .left
mike vorisis
  • 2,786
  • 6
  • 40
  • 74
codester
  • 36,891
  • 10
  • 74
  • 72
  • 3
    @codester .center doesn't seem to work if the text/content of a button is wrapped around to two lines. How can we centralise both lines of a button whose titleLabel has wrapped? – user2363025 Feb 02 '18 at 11:41
26

Swift 4

Sample code

For my requirement I want alignment left top

btnAddress.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left
btnAddress.contentVerticalAlignment = UIControlContentVerticalAlignment.top

Swift 5 update:

btnAddress.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.left
btnAddress.contentVerticalAlignment = UIControl.ContentVerticalAlignment.top
David Sanford
  • 735
  • 12
  • 26
Vivek
  • 4,916
  • 35
  • 40
2
    btnAddress.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.left
    btnAddress.contentVerticalAlignment = UIControl.ContentVerticalAlignment.top 

And now if you want the text to have some space from left add this

btnAddress.titleEdgeInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0)

Noman Haroon
  • 185
  • 1
  • 11
2

You can also use the below solution (using Storyboard)

step1 :

set the horizontal alignment to left enter image description here

By default button property have left content inset set to 10 i.e padding for the button from left side

you can see in the below image the left content inset is set to 10 for Left so change that to 0, if you don't need any padding from left or set the number you want

enter image description here

This way you can set the button title to Left aligned

Ashwini Salunkhe
  • 224
  • 2
  • 12
0

like this with swift 4:

btnAddress.contentHorizontalAlignment = .center
steveSarsawa
  • 1,559
  • 2
  • 14
  • 31
Dominik
  • 1,703
  • 6
  • 26
  • 46
-1

The Most Easiest and smallest Solution:

Button("0"){}.frame(width:160.0,height:70.0,alignment:Alignment.leading)

Check this by using this code for a button you will see that button text is now aligned to "LEFT"

Button with text Alignment LEFT