如何将UIButton的标题设置为左alignment?
我需要显示从UIButton
左侧的电子邮件地址,但它被放置在中心。
有没有办法将alignment设置到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];
设置contentHorizontalAlignment:
emailBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
您可能还想要调整左侧内容,否则文本将触及左侧边框:
emailBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
如果您不想在代码中进行调整,也可以使用界面构build器。 在这里,我将文本alignment并缩进一些:
不要忘记,你也可以在button中alignment图像:
在Swift 3+中:
button.contentHorizontalAlignment = .left
UIButton *btn; btn.contentVerticalAlignment = UIControlContentVerticalAlignmentTop; btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
使用emailBtn.titleEdgeInsets
比contentEdgeInsets
更好,以防你不想改变button内的整个内容位置。
这里解释了如何做到这一点,为什么它这样工作: http : //cocoathings.blogspot.com/2013/03/how-to-make-uibutton-text-left-or-right.html
@DyingCactus的代码有一个小错误。 这是正确的解决scheme添加一个UILabel到一个UIButtonalignmentbutton文本,以更好地控制button的“标题”:
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];
希望这可以帮助….
人
在xcode 8.2.1的界面生成器中,它将移动到:
对于Swift 2.0:
emailBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left
这可以帮助,如果任何人需要。
Swift 4+
button.contentHorizontalAlignment = .left button.contentVerticalAlignment = .top button.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)