如何将UIButton的标题设置为左对齐?

我需要显示UIButton左侧的电子邮件地址,但它位于中心。

有没有办法将对齐设置为UIButton的左侧?

这是我现在的代码:

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

设置contentHorizo​​ntalAlignment:

emailBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

您可能还想调整左侧内容,否则文本将触及左侧边框:

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

如果您不想在代码中进行调整,也可以使用界面构建器。 在这里,我将文本对齐并缩进一些:

IB中的UIButton

不要忘记,你也可以在按钮上对齐图像:

在这里输入图像描述


在Swift 3+中:

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

上一篇: How to set the title of UIButton as left alignment?

下一篇: How do I create a basic UIButton programmatically?