iOS自定义按钮拓展类,实现对按钮中图片和文字的任意布局

释放双眼,带上耳机,听听看~!

1、首先创建一个按钮的拓展类,Common+N,选择Object-C,点击确定后再选择Category,然后命名后确定创建

2、贴上代码

.h文件中

#import <UIKit/UIKit.h>
typedef NS_ENUM(NSUInteger, XCButtonEdgeInsetsStyle) {
XCButtonEdgeInsetsStyleTop,     // image在上,label在下
XCButtonEdgeInsetsStyleLeft,    // image在左,label在右
XCButtonEdgeInsetsStyleBottom,  // image在下,label在上
XCButtonEdgeInsetsStyleRight    // image在右,label在左
};
@interface UIButton (XCStyle)
- (void)XC_layoutButtonWithEdgeInsetsStyle:(XCButtonEdgeInsetsStyle)style
imageTitleSpace:(CGFloat)space;
@end

.m文件中


#import "UIButton+XCStyle.h"
@implementation UIButton (XCStyle)
- (void)XC_layoutButtonWithEdgeInsetsStyle:(XCButtonEdgeInsetsStyle)style
imageTitleSpace:(CGFloat)space
{
// 1. 得到imageView和titleLabel的宽、高
CGFloat imageWith = self.imageView.frame.size.width;
CGFloat imageHeight = self.imageView.frame.size.height;
CGFloat labelWidth = 0.0;
CGFloat labelHeight = 0.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得到imageEdgeInsets和labelEdgeInsets的值
switch (style) {
case XCButtonEdgeInsetsStyleTop:
{
imageEdgeInsets = UIEdgeInsetsMake(-labelHeight-space/2.0, 0, 0, -labelWidth);
labelEdgeInsets = UIEdgeInsetsMake(0, -imageWith, -imageHeight-space/2.0, 0);
}
break;
case XCButtonEdgeInsetsStyleLeft:
{
imageEdgeInsets = UIEdgeInsetsMake(0, -space/2.0, 0, space/2.0);
labelEdgeInsets = UIEdgeInsetsMake(0, space/2.0, 0, -space/2.0);
}
break;
case XCButtonEdgeInsetsStyleBottom:
{
imageEdgeInsets = UIEdgeInsetsMake(0, 0, -labelHeight-space/2.0, -labelWidth);
labelEdgeInsets = UIEdgeInsetsMake(-imageHeight-space/2.0, -imageWith, 0, 0);
}
break;
case XCButtonEdgeInsetsStyleRight:
{
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

人已赞赏
iOS文章

iOS数据持久化(NSUserDefault、Plist)

2020-3-30 15:46:53

iOS文章

ios pch的正确使用

2020-3-30 17:01:48

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索