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:
Don't forget you can also align an image in the button too.:
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.
Author by
Madan Mohan
Updated on July 26, 2022Comments
-
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 about 9 yearsThis helped me out a ton, can't believe I didn't realize that's what those controls were for.
-
Ashok almost 9 yearsThanks, 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 over 7 yearsin xcode 8.2.1 it moved to other place see my answer below
-
Visal Sambo over 5 yearsHow to do that programmatically in swift? I want align image on the right, and title on the left side???
-
danfordham over 4 yearsThis worked for me, contentHorizontalAlignment didn't, thanks.
-
jamryu almost 3 yearsWhat is the difference between .leading and .left value of contentHorizontalAlignment?