1、只有文字(默认居中)
1.1 文字居左显示
B66CABD9-882C-42FE-A528-8218740ADD93.png
代码实现:
btn02.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
// 也可调整左边间距
[btn02 setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 0)];
1.2 文字居右显示
代码实现:
btn02.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
// 调整右边间距
[btn02 setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 5)];
2、只有图片(默认居中显示)
2.1 图片居左显示
代码实现:
按钮属性
// how to position content vertically inside control. default is center
@property(nonatomic) UIControlContentVerticalAlignment contentVerticalAlignment;
// how to position content hozontally inside control. default is center
@property(nonatomic) UIControlContentHorizontalAlignment contentHorizontalAlignment;
设置属性,
btn02.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
2.2 图片居右显示
设置按钮属性:
btn02.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
// 设置右边间距为5,感觉不那么拥挤
[btn02 setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 5)];
3、文字 + 图片
3.1、左右-----图片在右 文字在左(默认的是图片在左,文字在右 在此不再赘述)
默认情况:
图片在右 文字在左:
代码实现:
// 先设置title,图片的x由title宽度决定
[btn02 setTitleEdgeInsets:UIEdgeInsetsMake(0, -btn02.imageView.width, 0, btn02.imageView.width)];
[btn02 setImageEdgeInsets:UIEdgeInsetsMake(0, btn02.titleLabel.width, 0, -btn02.titleLabel.width)];
3.2、上下-----图片在上 文字在下
代码实现:自定义按钮控件,重写-layoutSubviews方法
- (void)layoutSubviews
{
[super layoutSubviews]; // 不可少:布局初始化之后 再调整
// 调整image与title的frame
self.imageView.centerX = self.width * 0.5;
self.imageView.y = self.height * 0.5 - self.imageView.height; // 或者y=0
// 调整位置
[self.titleLabel sizeToFit]; // titleLabel宽高与文字占用空间一致
self.titleLabel.centerX = self.width * 0.5;
self.titleLabel.y = CGRectGetMaxY(self.imageView.frame)+5;// 上下间距是5
}