如果像UILabel一样设置UIButton文字对齐方式,会发现不起作用,还是默认的居中对齐,如下面代码:
UIButton *button = [[UIButton alloc] init];
[viewDad addSubview:button];
[button setTitle:@"我是按钮" forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button.titleLabel.textAlignment = NSTextAlignmentLeft; //这行不起作用
正确方法如下:
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
这样设置后会发现文字左边完全贴着按钮左边缘,不好看,设置文字左侧离按钮左边缘15点的距离:
button.titleEdgeInsets = UIEdgeInsetsMake(0., 15., 0., 0.);
问题完美解决!