UIButton的默认布局是:title在右,image在左;
很多时候我们需要的是title在左边,或者title在下面,这时就需要调整UIButton的TitleLabel和ImageView的位置了,查了很多资料,要么零零散散的介绍,要么就是特别复杂的实现;经过一段时间的学习,在这里总结一下实现的方式;
一种是设置UIButton的以下两个属性:
@property(nonatomic) UIEdgeInsets titleEdgeInsets; // default is UIEdgeInsetsZero
@property(nonatomic) UIEdgeInsets imageEdgeInsets; // default is UIEdgeInsetsZero
还有一种就是,自定义button,继承自UIButton,重写UIButton的以下两个方法:
- (CGRect)titleRectForContentRect:(CGRect)contentRect;
- (CGRect)imageRectForContentRect:(CGRect)contentRect;
下面来介绍这两种实现方式:
一,设置属性
1.修改为标题在左,图片在右样式
其属性的类型为UIEdgeInsets,为一个结构体:
typedef struct UIEdgeInsets {
CGFloat top, left, bottom, right; // specify amount to inset (positive) for each of the edges. values can be negative to 'outset'
} UIEdgeInsets;
表示 上 左 下 右的偏移量;解释下,这四个量的含义:
top : 为正数的时候,是往下偏移,为负数的时候往上偏移;
left : 为正数的时候往右偏移,为负数的时候往左偏移;
bottom : 为正数的时候往上偏移,为负数的时候往下偏移;
right :为正数的时候往左偏移,为负数的时候往右偏移;
在设置UIButton的这两个属性时,遇到的第一个问题就是偏移量设置为多少?很多介绍这种方法的使用的都是固定值,当按钮的frame改变时,需要改动很多地方,看的有点云里雾里的;
经过一些研究,发现还是有一些公共的东西可以使用的:
第一个想到的是UIButton的标题titleLabel的frame和imageView的frame,所以,先获取titleLabel和imageView的size:
CGSize titleSize = button.titleLabel.bounds.size;
CGSize imageSize = button.imageView.bounds.size;
然后设置UIButton的属性:
button.imageEdgeInsets = UIEdgeInsetsMake(0,titleSize.width, 0, -titleSize