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

当前回答

如果你使用按钮。contenttedgeinsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10),你会得到一个警告,声明“contenttedgeinsets”在iOS 15.0中已弃用:使用UIButtonConfiguration时忽略此属性。另一种解决方案是:

15、0 +。

    var button: UIButton = {
        let button = UIButton(configuration: .filled())

        button.configuration?.contentInsets = NSDirectionalEdgeInsets(top: 16, leading: 20, bottom: 16, trailing: 20)
        button.contentHorizontalAlignment = .leading
        
        return button
    }()

其他回答

斯威夫特 4+

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

@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

在Swift 3+中:

button.contentHorizontalAlignment = .left

如果您不想在代码中进行调整,也可以使用接口生成器。 这里我左对齐文本,也缩进一些:

别忘了你也可以在按钮中对齐图像。

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