Madan Mohan
Madan Mohan

Reputation: 8810

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

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];

Upvotes: 525

Views: 243305

Answers (15)

Muhammad Wasim
Muhammad Wasim

Reputation: 61

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

myButton.contentHorizontalAlignment = .left

Upvotes: 0

Nikolay Suvandzhiev
Nikolay Suvandzhiev

Reputation: 9055

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.

Upvotes: 1

Wes Chua
Wes Chua

Reputation: 1076

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
    }()

Upvotes: -1

user121301
user121301

Reputation:

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);

Upvotes: 1686

Gev
Gev

Reputation: 882

Try

button.semanticContentAttribute = UISemanticContentAttributeForceRightToLeft;

Upvotes: 2

Naresh
Naresh

Reputation: 17872

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

Upvotes: 2

Zaid Pathan
Zaid Pathan

Reputation: 16820

Swift 4+

button.contentHorizontalAlignment = .left
button.contentVerticalAlignment = .top
button.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)

Upvotes: 20

dang
dang

Reputation: 1588

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

Upvotes: 7

Vincent
Vincent

Reputation: 4409

In Swift 3+:

button.contentHorizontalAlignment = .left

Upvotes: 44

Suraj Sonawane
Suraj Sonawane

Reputation: 2484

For Swift 2.0:

emailBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left  

This can help if any one needed.

Upvotes: 3

bhavik
bhavik

Reputation: 1683

UIButton *btn;
btn.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

Upvotes: 15

n8tr
n8tr

Reputation: 5066

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

Upvotes: 127

Gabriel
Gabriel

Reputation: 101

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

Upvotes: 10

emkaka
emkaka

Reputation: 121

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

Upvotes: 8

Al-Noor Ladhani
Al-Noor Ladhani

Reputation: 2433

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

Upvotes: 5

Related Questions