UIButton文字居左显示

  1. 创建UIButton
UIButton *button = [[UIButton alloc] init];
//设置坐标
button.frame = CGRectMake(100, 100, 100, 50);
//设置标题
[button setTitle:@"我是UIButton" forState:UIControlStateNormal];
//设置标题颜色
[button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
//设置背景颜色    
[button setBackgroundColor:[UIColor orangeColor]];
[self.view addSubview:button];

以上代码是创建一个button,设置坐标、标题、和标题颜色。

  1. 让文字居左
    按照UILabel文字居左的写法,UIButton应该这么写:
 button.titleLabel.textAlignment = NSTextAlignmentLeft;```
我们发现UIButton的文字还是居中显示。竟然没有居左显示,怎么办呢?进UIButton看看,还有哪些属性。很快发现:

@property(nonatomic) UIControlContentHorizontalAlignment contentHorizontalAlignment; // how to position content hozontally inside control. default is center
typedef NS_ENUM(NSInteger, UIControlContentHorizontalAlignment) {
UIControlContentHorizontalAlignmentCenter = 0,
UIControlContentHorizontalAlignmentLeft = 1,
UIControlContentHorizontalAlignmentRight = 2,
UIControlContentHorizontalAlignmentFill = 3,
};

设置contentHorizontalAlignment

button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

![button_left.png](http://upload-images.jianshu.io/upload_images/1253942-71eb138d1d40bddb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
设置UIButton的titleEdgeInsets属性:

button.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);```
这样button的title就距左边10个像素的距离。

  1. 居右显示就很简单了:
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;```

你可能感兴趣的:(UIButton文字居左显示)