如何配置UIButton的title与Image的EdgeInsets
UIEdgeInsetsMake(top,left,bottom,right),它的作用是处理控件距离容器的上左下右的距离,可以为正值也可以是负值。下面的表格展示了正负值表现的效果
UIEdgeInsets | top | left | bottom | right |
---|---|---|---|---|
正值 | 向下偏移 | 向右偏移 | 向上偏移 | 向左偏移 |
负值 | 向上偏移 | 向左偏移 | 向下便宜 | 向右偏移 |
titleEdgeInsets是设置button标题的内边距。
imageEdgeInsets是设置button图片的内边距
button默认是图片在左,title在右,当我们需要处理他们的相对位置时,就需要调整EdgeInsets了。
image的right时相对于title的left的,当然title的left也是相对于image的right的。其他的都是相对于容器的边框的。
下面提供的工具方便修改button里image与title的相对位置
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSUInteger, ZekeButtonEdgeInsetsStyle) {
ZekeButtonEdgeInsetsStyleTop, // image在上,label在下
ZekeButtonEdgeInsetsStyleLeft, // image在左,label在右
ZekeButtonEdgeInsetsStyleBottom, // image在下,label在上
ZekeButtonEdgeInsetsStyleRight // image在右,label在左
};
@interface UIButton (ImageTitleSpacing)
/**
* 设置button的titleLabel和imageView的布局样式,及间距
*
* @param style titleLabel和imageView的布局样式
* @param space titleLabel和imageView的间距
*/
- (void)layoutButtonWithEdgeInsetsStyle:(ZekeButtonEdgeInsetsStyle)style
imageTitleSpace:(CGFloat)space;
@end
#import "UIButton+ImageTitleSpacing.h"
@implementation UIButton (ImageTitleSpacing)
- (void)layoutButtonWithEdgeInsetsStyle:(MKButtonEdgeInsetsStyle)style
imageTitleSpace:(CGFloat)space
{
/**
* 前置知识点:titleEdgeInsets是title相对于其上下左右的inset,跟tableView的contentInset是类似的,
* 如果只有title,那它上下左右都是相对于button的,image也是一样;
* 如果同时有image和label,那这时候image的上左下是相对于button,右边是相对于label的;title的上右下是相对于button,左边是相对于image的。
*/
// 1. 由于iOS8中titleLabelimageView的size为0,用下面的这种设置
CGFloat imageWith = self.imageView.intrinsicContentSize.width;
CGFloat imageHeight = self.imageView.intrinsicContentSize.height;
CGFloat labelWidth = self.titleLabel.intrinsicContentSize.width;
CGFloat labelHeight = self.titleLabel.intrinsicContentSize.height;
// 2. 声明全局的imageEdgeInsets和labelEdgeInsets
UIEdgeInsets imageEdgeInsets = UIEdgeInsetsZero;
UIEdgeInsets labelEdgeInsets = UIEdgeInsetsZero;
// 3. 根据style和space得到imageEdgeInsets和labelEdgeInsets的值
switch (style) {
case ZekeButtonEdgeInsetsStyleTop:
{
imageEdgeInsets = UIEdgeInsetsMake(-labelHeight-space/2.0, 0, 0, -labelWidth);
labelEdgeInsets = UIEdgeInsetsMake(0, -imageWith, -imageHeight-space/2.0, 0);
}
break;
case ZekeButtonEdgeInsetsStyleLeft:
{
imageEdgeInsets = UIEdgeInsetsMake(0, -space/2.0, 0, space/2.0);
labelEdgeInsets = UIEdgeInsetsMake(0, space/2.0, 0, -space/2.0);
}
break;
case ZekeButtonEdgeInsetsStyleBottom:
{
imageEdgeInsets = UIEdgeInsetsMake(0, 0, -labelHeight-space/2.0, -labelWidth);
labelEdgeInsets = UIEdgeInsetsMake(-imageHeight-space/2.0, -imageWith, 0, 0);
}
break;
case ZekeButtonEdgeInsetsStyleRight:
{
imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth+space/2.0, 0, -labelWidth-space/2.0);
labelEdgeInsets = UIEdgeInsetsMake(0, -imageWith-space/2.0, 0, imageWith+space/2.0);
}
break;
default:
break;
}
// 4. 赋值
self.titleEdgeInsets = labelEdgeInsets;
self.imageEdgeInsets = imageEdgeInsets;
}
@end