如果像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.);
問題完美解決!