不使用系统自带的button


//

//  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,strongUIFont * 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

{

//    记录button标题的字体

    self.myFont = [UIFont systemFontOfSize:15];

//    设置标题的字体

    self.titleLabel.font = self.myFont;

//    设置button的图片显示的内容默觉得拉伸不是居中

    self.imageView.contentMode = UIViewContentModeCenter;

    

}

//用于返回button上标题的位置,传入button的rect

-(CGRect)titleRectForContentRect:(CGRect)contentRect

{

    CGFloat titleX = 0;

    CGFloat titleY = 0;

    CGFloat titleW = 0;

    CGFloat titleH = contentRect.size.height;

//    获取button上的字体 1

    [self titleForState:UIControlStateNormal];

//    获取button上的字体2

    NSString * title = self.currentTitle;//建议使用这种方法 这种方法获得的是不论什么状态下的title

    CGSize maxSize = CGSizeMake(MAXFLOATMAXFLOAT);

    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 = button的宽度 - 图片的宽度

    CGFloat imageX= contentRect.size.width - imageW;

    return CGRectMake(imageX, imageY, imageW, imageH);

    

}

posted @ 2017-06-01 09:43  wzjhoutai  阅读(150)  评论(0编辑  收藏  举报