How to set the title of UIButton as left alignment?

I need to display the email address from left side of a UIButton , but it is being positioned in 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];

Set the contentHorizontalAlignment:

emailBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

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

emailBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);

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:

IB中的UIButton

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

在这里输入图像描述


在Swift 3+中:

button.contentHorizontalAlignment = .left
链接地址: http://www.djcxy.com/p/28214.html

上一篇: 更改UIButton文本

下一篇: 如何将UIButton的标题设置为左对齐?