mem*_*ons 29 cocoa-touch objective-c uibutton ios
问题:
一个按钮的设置后titleEdgeInset和UITextAlignmentLeft按钮的标题仍然是中心,不是以左对齐.
细节:
我有一个200px宽的按钮,使用自定义背景,左侧是图像.由于我不希望按钮标题覆盖图像,我使用了标题titleEdgeInset=UIEdgeInsetsMake(0.0, 45.0, 0.0, 0.0);.这应该使标题标签的x位置从45px开始并以200px结束.我还希望按钮的标题与图像左对齐,所以我也设置了textAlignment = UITextAlignmentLeft.但是,标题文本仍然在45px和200px之间居中,而不是左对齐.
为什么?
这是相关的代码:
button.titleEdgeInsets = UIEdgeInsetsMake(0.0, 45.0, 0.0, 0.0);
button.titleLabel.textAlignment = UITextAlignmentLeft;
[button setTitle:@"X"];
Run Code Online (Sandbox Code Playgroud)
rob*_*off 80
我的测试代码:
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(20, 20, 200, 72);
UIImage *image = [UIImage imageNamed:@"rob.png"];
[button setImage:image forState:UIControlStateNormal];
button.imageEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
[button setTitle:@"Hello" forState:UIControlStateNormal];
button.titleEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0);
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
[self.view addSubview:button];
Run Code Online (Sandbox Code Playgroud)
请注意,我button.contentHorizontalAlignment没有设置button.titleLabel.textAlignment.我的结果:

Vin*_* TP 22
为按钮设置contentHorizontalAlignment属性,它将起作用.
YourButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
Run Code Online (Sandbox Code Playgroud)
Swift 4.0
YourButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.center
Run Code Online (Sandbox Code Playgroud)