How to change Button Title Alignment in Swift?

IosSwiftUibutton

Ios Problem Overview


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?

Ios Solutions


Solution 1 - Ios

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

btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left

Swift 3.x

btn.contentHorizontalAlignment = .left

Solution 2 - Ios

#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

Solution 3 - Ios

    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)

Solution 4 - Ios

like this with swift 4:

btnAddress.contentHorizontalAlignment = .center

Solution 5 - Ios

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionderdidaView Question on Stackoverflow
Solution 1 - IoscodesterView Answer on Stackoverflow
Solution 2 - IosVivekView Answer on Stackoverflow
Solution 3 - IosNoman HaroonView Answer on Stackoverflow
Solution 4 - IosDominikView Answer on Stackoverflow
Solution 5 - IosArshdeep SinghView Answer on Stackoverflow