我需要在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];

当前回答

在Swift 3+中:

button.contentHorizontalAlignment = .left

其他回答

在xcode 8.2.1的接口构建器中,它移动到:

Try

button.semanticContentAttribute = UISemanticContentAttributeForceRightToLeft;

迅捷用户界面

你应该改变应用于文本的.frame修饰符的对齐属性。另外,将多行文本对齐设置为.leading。

Button {
    // handler for tapping on the button
} label: {
    Text("Label")
        .frame(width: 200, alignment: .leading)
        .multilineTextAlignment(.leading)
}

设置contentthorizontalalign:

// 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);

斯威夫特 4+

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