标签:
//
// LKTitleBtn.m
// 01-彩票
//
// Created by Lenny on 3/17/15.
// Copyright (c) 2015 Lenny. All rights reserved.
//
#import "LKTitleBtn.h"
#import <Availability.h>
@interface LKTitleBtn ()
@property(nonatomic,strong) UIFont * myFont;
@end
@implementation LKTitleBtn
-(id)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super initWithCoder:aDecoder])
{
[self setup];
}
return self;
}
-(instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
[self setup];
}
return self;
}
-(void)setup
{
// 记录按钮标题的字体
self.myFont = [UIFont systemFontOfSize:15];
// 设置标题的字体
self.titleLabel.font = self.myFont;
// 设置按钮的图片显示的内容默认为拉伸不是居中
self.imageView.contentMode = UIViewContentModeCenter;
}
//用于返回按钮上标题的位置,传入按钮的rect
-(CGRect)titleRectForContentRect:(CGRect)contentRect
{
CGFloat titleX = 0;
CGFloat titleY = 0;
CGFloat titleW = 0;
CGFloat titleH = contentRect.size.height;
// 获取按钮上的字体 1
[self titleForState:UIControlStateNormal];
// 获取按钮上的字体2
NSString * title = self.currentTitle;//建议使用这个方法 这个方法获得的是任何状态下的title
CGSize maxSize = CGSizeMake(MAXFLOAT, MAXFLOAT);
NSMutableDictionary * md = [NSMutableDictionary dictionary];
// 死循环的原因是self.titleLabel需要访问titleLabel, 而self.titleLabel又需要调用当前方法获取title的范围, 所有死循环
// md[NSFontAttributeName] = self.titleLabel.font;
// NSLog(@"%@", self.myFont);
md[NSFontAttributeName] = self.myFont;
// 计算文字的范围
// 判断是否是xcode5 , 如果是就编译一下代码, 如果不是就不编译
#ifdef __IPHONE_7_0
if (([[UIDevice currentDevice].systemVersion doubleValue] >= 7.0)) {
CGRect titleRect = [title boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:md context:nil];
titleW = titleRect.size.width;
}else{
CGSize titleSize = [title sizeWithFont:self.myFont];//过时的方法
titleW = titleSize.width;
}
#else
// XCODE4
CGSize titleSize = [title sizeWithFont:self.myFont];
titleW = titleSize.width;
#endif
return CGRectMake(titleX, titleY, titleW, titleH);
}
-(CGRect)imageRectForContentRect:(CGRect)contentRect{
CGFloat imageY = 0;
CGFloat imageH = contentRect.size.height;
CGFloat imageW = 16;//图片的宽度
// 图片的X = 按钮的宽度 - 图片的宽度
CGFloat imageX= contentRect.size.width - imageW;
return CGRectMake(imageX, imageY, imageW, imageH);
}
标签:
原文地址:http://blog.csdn.net/guoyule2010/article/details/44407825