525

I need to display an email address on the left side of a UIButton, but it is being positioned to the centre.

Is there any way to set the alignment to the left side of a UIButton?

This is my current code:

UIButton* emailBtn = [[UIButton alloc] initWithFrame:CGRectMake(5,30,250,height+15)];
emailBtn.backgroundColor = [UIColor clearColor];
[emailBtn setTitle:obj2.customerEmail forState:UIControlStateNormal];
emailBtn.titleLabel.font = [UIFont systemFontOfSize:12.5];
[emailBtn setTitleColor:[[[UIColor alloc]initWithRed:0.121 green:0.472 blue:0.823 alpha:1]autorelease] forState:UIControlStateNormal];
[emailBtn addTarget:self action:@selector(emailAction:) forControlEvents:UIControlEventTouchUpInside];
[elementView addSubview:emailBtn];
[emailBtn release];
1

15 Answers 15

1686

Set the contentHorizontalAlignment:

// Swift 
emailBtn.contentHorizontalAlignment = .left;

// Objective-C
emailBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

You might also want to adjust the content left inset otherwise the text will touch the left border:

// Swift 3 and up:
emailBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0);

// Objective-C
emailBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
7
  • 49
    Keep in mind that you can also set both of these properties from Interface Builder. Commented Feb 1, 2013 at 8:49
  • 1
    so it was number 9000 from me, thanx , useful answer
    – Logic
    Commented May 25, 2015 at 13:02
  • 9
    We're too lazy to search the documentation. What would we do without SO! Commented Nov 24, 2015 at 6:48
  • 5
    Goes to show SO is better documented than Apple document.
    – GeneCode
    Commented Oct 13, 2016 at 10:46
  • 2
    UIControlContentHorizontalAlignmentLeading and UIControlContentHorizontalAlignmentTrailing were added in iOS 11 Commented Jan 6, 2018 at 1:48
127

You can also use interface builder if you don't want to make the adjustments in code. Here I left align the text and also indent it some:

UIButton in IB

Don't forget you can also align an image in the button too.:

enter image description here

4
  • This helped me out a ton, can't believe I didn't realize that's what those controls were for. Commented May 18, 2015 at 17:54
  • 1
    Thanks, It helped me. I was not able to find out edge insets for button title without the help of arrow indication in your sample pictures.
    – Ashok
    Commented Jul 9, 2015 at 9:55
  • in xcode 8.2.1 it moved to other place see my answer below
    – dang
    Commented Jan 27, 2017 at 12:56
  • How to do that programmatically in swift? I want align image on the right, and title on the left side??? Commented Aug 26, 2018 at 15:52
44

In Swift 3+:

button.contentHorizontalAlignment = .left
2
  • What is the difference between .leading and .left value of contentHorizontalAlignment?
    – jamryu
    Commented Jul 16, 2021 at 21:22
  • @jamryu that in case of languages where you write from right to left (arabic I think..?) .leading will have same effect as .right.
    – Nat
    Commented Jul 21, 2022 at 14:08
20

Swift 4+

button.contentHorizontalAlignment = .left
button.contentVerticalAlignment = .top
button.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
15
UIButton *btn;
btn.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
10

Using emailBtn.titleEdgeInsets is better than contentEdgeInsets, in case you don't want to change the whole content position inside the button.

8

Here is explained how to do it and why it works so: http://cocoathings.blogspot.com/2013/03/how-to-make-uibutton-text-left-or-right.html

7

in xcode 8.2.1 in the interface builder it moves to:enter image description here

5

There is a small error in the code of @DyingCactus. Here is the correct solution to add an UILabel to an UIButton to align the button text to better control the button 'title':

NSString *myLabelText = @"Hello World";
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];

// position in the parent view and set the size of the button
myButton.frame = CGRectMake(myX, myY, myWidth, myHeight); 

CGRect myButtonRect = myButton.bounds;
UILabel *myLabel = [[UILabel alloc] initWithFrame: myButtonRect];   
myLabel.text = myLabelText;
myLabel.backgroundColor = [UIColor clearColor];
myLabel.textColor = [UIColor redColor]; 
myLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:14.0];   
myLabel.textAlignment = UITextAlignmentLeft;

[myButton addSubview:myLabel];
[myLabel release];

Hope this helps....

Al

0
3

For Swift 2.0:

emailBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left  

This can help if any one needed.

2

In Swift 5.0 and Xcode 10.2

You have two ways to approaches

1) Direct approach

btn.contentHorizontalAlignment = .left

2) SharedClass example (write once and use every ware)

This is your shared class(like this you access all components properties)

import UIKit

class SharedClass: NSObject {

    static let sharedInstance = SharedClass()

    private override init() {

    }
}

//UIButton extension
extension UIButton {
    func btnProperties() {
        contentHorizontalAlignment = .left
    }
}

In your ViewController call like this

button.btnProperties()//This is your button
2

Try

button.semanticContentAttribute = UISemanticContentAttributeForceRightToLeft;
1
  • 1
    This worked for me, contentHorizontalAlignment didn't, thanks.
    – danfordham
    Commented Sep 14, 2019 at 18:05
1

tl;dr: Using UIButton.Configuration - do titleAlignment = .center but also add a subtitle and make its font microscopic.


So, we're on iOS 15+, we're using the new UIButton.Configuration APIs, buttons now go multi-line by default and you're trying to figure out - how do I make the button's title be centered or trailing aligned, as opposed to the default (leading). For example you have an image and a button title underneath and and you want it centered.

enter image description here

Seems reasonable to try this:

configuration.titleAlignment = .center

But it doesn't change anything.

By trying thing out in Interface Builder, I noticed the following: titleAlignment only has an effect if there is a subtitle along with the title.

enter image description here

I am not sure if this is an omission on Apple's side (which might be fixed later) or if there is a good reason for it. In any case, we need a way to make it work without a subtitle. Perhaps some clever contentInset or UIControl.contentHorizontalAlignment can do the trick, but I'd be worried to use these in cases where we have to think about other languages, dynamic type etc.

Here's a solution which is still hacky, but would do the job: Add a subtitle which contains just a space, then make the font microscopic, e.g. 0.01.

This is how to do it in code, assuming you are already working with a UIButton.Configuration:

configuration.titleAlignment = .center
configuration.title = "Hello hi"
configuration.subtitle = " "
configuration.subtitleTextAttributesTransformer = UIConfigurationTextAttributesTransformer({ input in
    var output = input
    output.font = .systemFont(ofSize: 0.01)
    return output
})

Not an ideal solution and it might break in the future, but for some use cases the best available solution at the moment.

1
  • Indeed, titleAlignment is only for aligning the title and subtitle relative to each other. To set the alignment of the title itself, you can use an AttributedString with a paragraph style: let style = NSMutableParagraphStyle(); style.alignment = .center; configuration.attributedTitle = .init("Hello hi", attributes: .init([.paragraphStyle: paragraphStyle]))
    – dbplunkett
    Commented Oct 23, 2024 at 19:21
0

With Swift 3+ you can do it simply with one line:

myButton.contentHorizontalAlignment = .left
-1

if you use button.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10), you will get an warning that states 'contentEdgeInsets' was deprecated in iOS 15.0: This property is ignored when using UIButtonConfiguration. An alternative solution is:

iOS 15.0+

    var button: UIButton = {
        let button = UIButton(configuration: .filled())

        button.configuration?.contentInsets = NSDirectionalEdgeInsets(top: 16, leading: 20, bottom: 16, trailing: 20)
        button.contentHorizontalAlignment = .leading
        
        return button
    }()

Not the answer you're looking for? Browse other questions tagged or ask your own question.