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

226,522

Solution 1

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

Solution 2

In Swift 3+:

button.contentHorizontalAlignment = .left

Solution 3

Swift 4+

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

Solution 4

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

Solution 5

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

Share:
226,522
Madan Mohan
Author by

Madan Mohan

Updated on July 26, 2022

Comments

  • Madan Mohan
    Madan Mohan almost 2 years

    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];
    
  • Ethan Parker
    Ethan Parker about 9 years
    This helped me out a ton, can't believe I didn't realize that's what those controls were for.
  • Ashok
    Ashok almost 9 years
    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.
  • dang
    dang over 7 years
    in xcode 8.2.1 it moved to other place see my answer below
  • Visal Sambo
    Visal Sambo over 5 years
    How to do that programmatically in swift? I want align image on the right, and title on the left side???
  • danfordham
    danfordham over 4 years
    This worked for me, contentHorizontalAlignment didn't, thanks.
  • jamryu
    jamryu almost 3 years
    What is the difference between .leading and .left value of contentHorizontalAlignment?