传入button中自带的文本和图片的样式,即可很容易在button上面按照设置的同时显示图片和文字,不需要其他调整,代码如下:
.h文件
#import <UIKit/UIKit.h>
@interface MyButton : UIButton
@property(nonatomic,assign) CGRect titleFrame;
@property(nonatomic,assign) CGRect imageFrame;
//增加button的一个可选或其他用途的属性
@property(nonatomic,assign)BOOL isSel;
@end
.m 文件
#import "MyButton.h"
@implementation MyButton
- (void)drawRect:(CGRect)rect {
// button的文字图片等一些属性在这里设置
[self setTitleColor:[UIColor colorWithRed:119 / 255.0 green:120 / 255.0 blue:121 / 255.0 alpha:1] forState:UIControlStateNormal];
self.titleLabel.font = [UIFont systemFontOfSize:15];
self.backgroundColor = [UIColor clearColor];
}
- (instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self != nil) {
// 设置文本样式(这里是居中)
self.titleLabel.textAlignment = NSTextAlignmentRight;
// 设置图片的内容模式(这里是左边)
self.imageView.contentMode = UIViewContentModeLeft;
}
return self;
}
#pragma mark - 方法一
/*
重新titleRectForContentRect: 和 imageRectForContentRect:
这两个方法修改文本内容位置和图片内容位置
*/
// 修改文本内容位置
- (CGRect)titleRectForContentRect:(CGRect)contentRect{
return _titleFrame;
}
// 修改图片内容位置
- (CGRect)imageRectForContentRect:(CGRect)contentRect{
return _imageFrame;
}