使用自定义控件来代替UIButton显示图文与标题
自带的UIbutton图片大小和位置实在太难自定义了。
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSInteger, ImagePosition) {
ImagePositionTop, // 图片在上,标题在下
ImagePositionBottom, // 图片在下,标题在上
ImagePositionLeft, // 图片在左,标题在右
ImagePositionRight // 图片在右,标题在左
};
@interface ImageTitleView : UIControl
@property (nonatomic, strong) UIImageView *imageView; // 图片视图
@property (nonatomic, strong) UILabel *titleLabel; // 标题标签
@property (nonatomic, assign) ImagePosition imagePosition; // 图片位置,默认为图片在上,标题在下
// 点击事件的回调
@property (nonatomic, copy) void (^tapBlock)(ImageTitleView *view);
@end
@implementation ImageTitleView
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
// 初始化图片视图
_imageView = [[UIImageView alloc] init];
_imageView.contentMode = UIViewContentModeScaleAspectFit; // 设置图片的内容模式为等比缩放
[self addSubview:_imageView];
// 初始化标题标签
_titleLabel = [[UILabel alloc] init];
_titleLabel.textAlignment = NSTextAlignmentCenter; // 设置标题的对齐方式为居中
_titleLabel.textColor = [UIColor blackColor]; // 设置标题的颜色为黑色
[self addSubview:_titleLabel];
// 设置默认图片位置为图片在上,标题在下
_imagePosition = ImagePositionTop;
// 添加点击事件
[self addTarget:self action:@selector(handleTap:) forControlEvents:UIControlEventTouchUpInside];
}
return self;
}
- (void)layoutSubviews {
[super layoutSubviews];
CGFloat width = self.bounds.size.width;
CGFloat height = self.bounds.size.height;
switch (self.imagePosition) {
case ImagePositionTop:
self.imageView.frame = CGRectMake(0, 0, width, height/2);
self.titleLabel.frame = CGRectMake(0, height/2, width, height/2);
break;
case ImagePositionBottom:
self.imageView.frame = CGRectMake(0, height/2, width, height/2);
self.titleLabel.frame = CGRectMake(0, 0, width, height/2);
break;
case ImagePositionLeft:
self.imageView.frame = CGRectMake(0, 0, width/2, height);
self.titleLabel.frame = CGRectMake(width/2, 0, width/2, height);
break;
case ImagePositionRight:
self.imageView.frame = CGRectMake(width/2, 0, width/2, height);
self.titleLabel.frame = CGRectMake(0, 0, width/2, height);
break;
default:
break;
}
}
- (void)handleTap:(ImageTitleView *)view {
if (self.tapBlock) {
self.tapBlock(view);
}
}
@end
发表回复