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

其他回答

@DyingCactus的代码有一个小错误。 下面是正确的解决方案,添加一个UILabel到UIButton来对齐按钮文本,以更好地控制按钮的“标题”:

NSString *myLabelText = @"Hello World";
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];

// position in the parent view and set the size of the button
myButton.frame = CGRectMake(myX, myY, myWidth, myHeight); 

CGRect myButtonRect = myButton.bounds;
UILabel *myLabel = [[UILabel alloc] initWithFrame: myButtonRect];   
myLabel.text = myLabelText;
myLabel.backgroundColor = [UIColor clearColor];
myLabel.textColor = [UIColor redColor]; 
myLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:14.0];   
myLabel.textAlignment = UITextAlignmentLeft;

[myButton addSubview:myLabel];
[myLabel release];

希望这有助于....

Al

使用emailBtn。titleEdgeInsets比contenttedgeinsets更好,如果你不想改变按钮内的整个内容位置。

在Swift 5.0和Xcode 10.2中

有两种方法

1)直接方法

btn.contentHorizontalAlignment = .left

2) SharedClass示例(编写一次,然后使用每个ware)

这是您的共享类(像这样您可以访问所有组件属性)

import UIKit

class SharedClass: NSObject {

    static let sharedInstance = SharedClass()

    private override init() {

    }
}

//UIButton extension
extension UIButton {
    func btnProperties() {
        contentHorizontalAlignment = .left
    }
}

在你的ViewController调用中

button.btnProperties()//This is your button

设置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);

在Swift 3+中:

button.contentHorizontalAlignment = .left