ios - 如何将 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:

// Swift 
emailBtn.contentHorizontalAlignment = .left;

// Objective-C
emailBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

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

// Swift 3 and up:
emailBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0);

// Objective-C
emailBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);

https://stackoverflow.com/questions/2765024/

相关文章:

objective-c - 如何迭代 NSArray?

objective-c - 如何将百分号添加到 NSString

c - 是否可以使用 NSLog C 结构(如 CGRect 或 CGPoint)?

ios - @import 与 #import - iOS 7

objective-c - "__block"关键字是什么意思?

ios - 在 iOS 中获取当前设备语言?

objective-c - 类方法和实例方法有什么区别?

objective-c - 如何打印出方法名称和行号并有条件地禁用 NSLog?

objective-c - 在objective-c/cocoa中抛出异常

ios - AVFoundation, captureStillImageAsynchronousl