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

Mad*_*han 458 objective-c uibutton

我需要从a的左侧显示电子邮件地址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];
Run Code Online (Sandbox Code Playgroud)

小智 1544

设置contentHorizo​​ntalAlignment:

emailBtn.contentHorizontalAlignment = .left;
Run Code Online (Sandbox Code Playgroud)

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

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

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

  • 请记住,您还可以从Interface Builder中设置这两个属性. (44认同)
  • 我们懒得搜索文档.没有SO我们会做什么! (6认同)
  • 证明SO比Apple文件更好地记录在案。 (3认同)
  • iOS 11 添加了`UIControlContentHorizo​​ntalAlignmentLeading` 和`UIControlContentHorizo​​ntalAlignmentTrailing` (2认同)

n8t*_*8tr 118

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

IB中的UIButton

别忘了你也可以在按钮上对齐图像:

在此输入图像描述


Vin*_*ent 34

在Swift 3+中:

button.contentHorizontalAlignment = .left
Run Code Online (Sandbox Code Playgroud)


bha*_*vik 13

UIButton *btn;
btn.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
Run Code Online (Sandbox Code Playgroud)


Zai*_*han 13

Swift 4+

button.contentHorizontalAlignment = .left
button.contentVerticalAlignment = .top
button.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
Run Code Online (Sandbox Code Playgroud)


小智 9

使用emailBtn.titleEdgeInsets优于contentEdgeInsets,如果您不想更改按钮内的整个内容位置.


dan*_*ang 6

在接口构建器中的xcode 8.2.1中,它移至:在此处输入图片说明


Al-*_*ani 5

@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];
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助....