您的位置:首页 > 产品设计 > UI/UE

UIButton文字居左显示

2015-08-25 17:00 316 查看


UILabel文字居左显示

实现文字居左显示代码如下:

UILabel *label = [[UILabel alloc] init];
label.frame = CGRectMake(50, 100, 200, 50);
label.text = @"Label is me";
label.textAlignment = UITextAlignmentLeft;
label.backgroundColor = [UIColor orangeColor];
[self.view addSubview:label];


运行的效果如下:


label.backgroundColor = [UIColor orangeColor]; 设置label的背景颜色方便我们参考。

UIButton文字居左显示

创建UIButton
// 创建按钮对象
UIButton *button = [[UIButton alloc] init];
// 设置坐标
button.frame = CGRectMake(100, 100, 150, 100);
// 设置标题
[button setTitle:@"button for JH" forState:UIControlStateNormal];
// 设置标题颜色
[button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
// 设置背景颜色
[button setBackgroundColor:[UIColor orangeColor]];
[self.view addSubview:button];




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

让文字居左

按照UILabel文字居左的写法,UIButton应该这么写:
button.titleLabel.textAlignment = NSTextAlignmentLeft;
运行效果如下:






我们发现UIButton的文字还是居中显示。竟然没有居左显示, HOW TO DO? 先进去->UIButton->UIControl看看,还有哪些属性。我们很快就发现:

typedef NS_ENUM(NSInteger, UIControlContentVerticalAlignment) {
UIControlContentVerticalAlignmentCenter  = 0,
UIControlContentVerticalAlignmentTop     = 1,
UIControlContentVerticalAlignmentBottom  = 2,
UIControlContentVerticalAlignmentFill    = 3,
};

typedef NS_ENUM(NSInteger, UIControlContentHorizontalAlignment) {
UIControlContentHorizontalAlignmentCenter = 0,
UIControlContentHorizontalAlignmentLeft   = 1,
UIControlContentHorizontalAlignmentRight  = 2,
UIControlContentHorizontalAlignmentFill   = 3,
};


设置contentHorizontalAlignment

button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;






果然可以,是不是看着居左显示很难看,太靠边了。很简单,设置UIButton的titleEdgeInsets属性:

button.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);


这样button的title就距左边10个像素的距离。
居右显示就简单了:

button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;


enen.UIButton文字居左显示完成了。 谢谢。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: