为了防止丢失或遗忘,记录下这个UIButton的分类,用来实现上下,左右的iamge与title位置的按钮布局。
.h文件
#import@interface UIButton (typeLayout)
typedef NS_ENUM(NSUInteger,HLButtonEdgeInsetsStyle)
{
HLButtonEdgeInsetsStyleTop,//image在上,label在下
HLButtonEdgeInsetsStyleLeft,//image在左,label在右
HLButtonEdgeInsetsStyleBottom,//image在下,label在上
HLButtonEdgeInsetsStyleRight//image在右,label在左
};
/**
* 设置button内部的image和title的布局样式
*
* @param style 布局样式
* @param space 间距
*/
- (void)layoutButtonWithEdgeInsetsStyle:(HLButtonEdgeInsetsStyle)style imageTitleSpace:(CGFloat)space;
@end
.m文件
#import "UIButton+typeLayout.h"
@implementation UIButton (typeLayout)
- (void)layoutButtonWithEdgeInsetsStyle:(HLButtonEdgeInsetsStyle)style imageTitleSpace:(CGFloat)space
{
//1、得到imageView和titleLabel的宽、高
CGFloat imageWidth = self.imageView.frame.size.width;
CGFloat imageHeight = self.imageView.frame.size.height;
CGFloat labelWidth = 0;
CGFloat labelHeight = 0;
if([UIDevice currentDevice].systemVersion.floatValue >=8.0)
{
//由于iOS8中titleLabel的size为0,分开设置
labelWidth = self.titleLabel.intrinsicContentSize.width;
labelHeight = self.titleLabel.intrinsicContentSize.height;
}
else
{
labelWidth = self.titleLabel.frame.size.width;
labelHeight = self.titleLabel.frame.size.height;
}
//2、声明全局的imageEdgeInsets和labelEdgeInsets
UIEdgeInsets imageEdgeInsets = UIEdgeInsetsZero;
UIEdgeInsets labelEdgeInsets = UIEdgeInsetsZero;
//3、根据style和space设置
switch (style) {
case HLButtonEdgeInsetsStyleTop:
imageEdgeInsets = UIEdgeInsetsMake(-labelHeight-space/2.0, 0, 0, -labelWidth);
labelEdgeInsets = UIEdgeInsetsMake(0, -imageWidth, -imageHeight-space/2.0, 0);
break;
case HLButtonEdgeInsetsStyleLeft:
imageEdgeInsets = UIEdgeInsetsMake(0, -space/2.0, 0, space/2.0);
labelEdgeInsets = UIEdgeInsetsMake(0, space/2.0, 0, space/2.0);
break;
case HLButtonEdgeInsetsStyleBottom:
imageEdgeInsets = UIEdgeInsetsMake(0, 0, -labelHeight-space/2.0, -labelWidth);
labelEdgeInsets = UIEdgeInsetsMake(-labelHeight-space/2.0, 0, -imageWidth, 0);
break;
case HLButtonEdgeInsetsStyleRight:
imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth+space/2.0, 0, -labelWidth-space/2.0);
labelEdgeInsets = UIEdgeInsetsMake(0, -imageWidth - space/2.0, 0, imageWidth+space/2.0);
break;
default:
break;
}
self.titleEdgeInsets = labelEdgeInsets;
self.imageEdgeInsets = imageEdgeInsets;
}
@end
直接调用,方便快捷!