1 #import <UIKit/UIKit.h>
2
3 @interface NJTitleButton : UIButton
4
5 @end
6
7
8 #import "NJTitleButton.h"
9
10 @interface NJTitleButton ()
11 @property (nonatomic, strong) UIFont *myFont;
12 @end
13
14 @implementation NJTitleButton
15
16 - (id)initWithCoder:(NSCoder *)aDecoder
17 {
18
19 if (self = [super initWithCoder:aDecoder]) {
20 [self setup];
21 }
22 return self;
23 }
24
25 - (id)initWithFrame:(CGRect)frame
26 {
27 if (self = [super initWithFrame:frame]) {
28 [self setup];
29 }
30 return self;
31 }
32 - (void)setup
33 {
34 // 记录按钮标题的字体
35 self.myFont = [UIFont systemFontOfSize:15];
36 // 设置标题的字体
37 self.titleLabel.font = self.myFont;
38 // 设置按钮的图片显示的内容默认为剧中(为了不拉伸)
39 self.imageView.contentMode = UIViewContentModeCenter;
40 }
41
42 // 用于返回按钮上标题的位置, 传入按钮的rect
43 - (CGRect)titleRectForContentRect:(CGRect)contentRect
44 {
45 CGFloat titleX = 0;
46 CGFloat titleY = 0;
47 CGFloat titleH = contentRect.size.height;
48 // 获取当前按钮上的文字
49 // [self titleForState:UIControlStateNormal];
50 NSString *title = self.currentTitle;
51 CGSize maxSize = CGSizeMake(MAXFLOAT, MAXFLOAT);
52 NSMutableDictionary *md = [NSMutableDictionary dictionary];
53 // 死循环的原因是self.titleLabel需要访问titleLabel, 而self.titleLabel又需要调用当前方法获取title的范围, 所有死循环
54 // md[NSFontAttributeName] = self.titleLabel.font;
55 NSLog(@"%@", self.myFont);
56 md[NSFontAttributeName] = self.myFont;
57
58 // 计算文字的范围
59 CGFloat titleW = 0;
60 // 判断是否是xcode5 , 如果是就编译一下代码, 如果不是就不编译
61 CGRect titleRect = [title boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:md context:nil];
62 titleW = titleRect.size.width;
63
64 return CGRectMake(titleX, titleY, titleW, titleH);
65 }
66 - (CGRect)imageRectForContentRect:(CGRect)contentRect
67 {
68
69 CGFloat imageY = 0;
70 CGFloat imageH = contentRect.size.height;
71 CGFloat imageW = 16;
72 // 图片的X = 按钮的宽度 - 图片宽度
73 CGFloat imageX = contentRect.size.width - imageW;
74 return CGRectMake(imageX, imageY, imageW, imageH);
75 }
76 @end