How can I set the title of a UIButton as left-aligned?
Asked Answered
D

14

523

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];
Diffractive answered 4/5, 2010 at 11:56 Comment(1)
For Swift 5.1 you can look my answer #2765524Crumbly
B
1678

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);
Braud answered 4/5, 2010 at 12:22 Comment(6)
Keep in mind that you can also set both of these properties from Interface Builder.Zirkle
so it was number 9000 from me, thanx , useful answerThenceforward
We're too lazy to search the documentation. What would we do without SO!Physicality
Goes to show SO is better documented than Apple document.Synchro
Is it possible to use Leading or Trailing rather than Right or Left? (for localisation purposes)Penicillium
UIControlContentHorizontalAlignmentLeading and UIControlContentHorizontalAlignmentTrailing were added in iOS 11Seel
I
125

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

Inkster answered 29/3, 2014 at 0:13 Comment(4)
This helped me out a ton, can't believe I didn't realize that's what those controls were for.Outdoor
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.Circular
in xcode 8.2.1 it moved to other place see my answer belowPrevaricator
How to do that programmatically in swift? I want align image on the right, and title on the left side???Pyatt
C
44

In Swift 3+:

button.contentHorizontalAlignment = .left
Comstockery answered 1/9, 2015 at 6:6 Comment(2)
What is the difference between .leading and .left value of contentHorizontalAlignment?Larcener
@Larcener that in case of languages where you write from right to left (arabic I think..?) .leading will have same effect as .right.Tifanie
B
20

Swift 4+

button.contentHorizontalAlignment = .left
button.contentVerticalAlignment = .top
button.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
Bennir answered 22/9, 2017 at 11:37 Comment(0)
P
15
UIButton *btn;
btn.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
Poche answered 30/8, 2014 at 4:58 Comment(0)
H
10

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

Holliholliday answered 30/8, 2013 at 4:42 Comment(0)
D
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

Donothingism answered 6/3, 2013 at 17:2 Comment(0)
P
7

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

Prevaricator answered 27/1, 2017 at 12:55 Comment(0)
Y
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

Yippie answered 3/1, 2011 at 22:59 Comment(0)
S
3

For Swift 2.0:

emailBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left  

This can help if any one needed.

Satterlee answered 2/12, 2015 at 12:31 Comment(0)
F
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
Federicofedirko answered 29/4, 2019 at 5:10 Comment(0)
D
2

Try

button.semanticContentAttribute = UISemanticContentAttributeForceRightToLeft;
Demodulation answered 18/6, 2019 at 14:14 Comment(1)
This worked for me, contentHorizontalAlignment didn't, thanks.Beamends
S
0

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.

Shillong answered 17/1, 2023 at 12:27 Comment(0)
C
-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
    }()
Canaanite answered 11/10, 2022 at 14:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.