一种UIBarButtonItem的简单封装

版本记录

版本号 时间
V1.0 2017.08.04

前言

我们的app一般都需要导航栏,极个别的除外,比如说很多游戏是没有导航栏的,但是绝大部分是都有的,只要有导航栏就需要显示主题,左右item的图片或者文字,并且需要处理相关的事件,这里我就简单的封装了一个UIBarButtonItem的分类,可以快速的实现左右item图片和文字的显示,并预留了相关接口。整个框架只依赖苹果的API,不依赖其他第三方,拖入即可使用,简单方便。

预先了解

我这里写的是UIBarButtonItem的分类,可以实现导航左右item的文字以及图片的显示,并可响应相应的方法。


框架实现

下面我们就看一下所写框架的全部代码。

1. UIBarButtonItem+JJBarButtonItem.h
#import <UIKit/UIKit.h>

@interface UIBarButtonItem (JJBarButtonItem)


/**
 *   该函数的功能返回导航的leftItem
 *
 *   @param target :目标
 *   @param selector :响应方法
 *   @param imageNormal :正常的图片
 *   @param imageHightlighted :高亮的图片
 *   @param titleColorNormal :正常文字颜色
 *   @param titleColorHightlighted :高亮文字颜色
 *   @param title :文字
 *
 *   @return 左边UIBarButtonItem
 */
+ (UIBarButtonItem *)jjLeftItem:(id)target
                        selector:(SEL)selector
                     imageNormal:(UIImage *)imageNormal
               imageHightlighted:(UIImage *)imageHightlighted
                titleColorNormal:(UIColor *)titleColorNormal
          titleColorHightlighted:(UIColor *)titleColorHightlighted
                           title:(NSString *)title;

/**
 *   该函数的功能返回导航的rightItem
 *
 *   @param target :目标
 *   @param selector :响应方法
 *   @param imageNormal :正常的图片
 *   @param imageHightlighted :高亮的图片
 *   @param imageDisabled :无法点击的图片
 *   @param titleColorNormal :正常文字颜色
 *   @param titleColorHightlighted :高亮文字颜色
 *   @param titleColorDisabled :无法点击的文字
 *   @param title :文字
 *
 *   @return 右边UIBarButtonItem
 */
+ (UIBarButtonItem *)jjRightItem:(id)target
                         selector:(SEL)selector
                      imageNormal:(UIImage *)imageNormal
                imageHightlighted:(UIImage *)imageHightlighted
                    imageDisabled:(UIImage *)imageDisabled
                 titleColorNormal:(UIColor *)titleColorNormal
           titleColorHightlighted:(UIColor *)titleColorHightlighted
               titleColorDisabled:(UIColor *)titleColorDisabled
                            title:(NSString *)title;

//几种简化默认返回简化写法

+ (UIBarButtonItem *)jjDefaultBackItem:(id)target
                               selector:(SEL)selector
                                  title:(NSString *)title;

+ (UIBarButtonItem *)jjDefaultBackItem:(id)target
                               selector:(SEL)selector
                       titleColorNormal:(UIColor *)titleColorNormal
                 titleColorHightlighted:(UIColor *)titleColorHightlighted
                                  title:(NSString *)title;

+ (UIBarButtonItem *)jjDefaultRightTitleItem:(id)target
                                     selector:(SEL)selector
                                        title:(NSString *)title;

+ (UIBarButtonItem *)jjDefaultRightItem:(id)target
                                selector:(SEL)selector
                        titleColorNormal:(UIColor *)titleColorNormal
                  titleColorHightlighted:(UIColor *)titleColorHightlighted
                      titleColorDisabled:(UIColor *)titleColorDisabled
                                   title:(NSString *)title;

+ (UIBarButtonItem *)jjDefaultRightImageItem:(id)target
                                     selector:(SEL)selector
                                  imageNormal:(UIImage *)imageNormal
                            imageHightlighted:(UIImage *)imageHightlighted
                                imageDisabled:(UIImage *)imageDisabled;

- (UIButton *)jjContentViewButton;

@end
2. UIBarButtonItem+JJBarButtonItem.m
#import "UIBarButtonItem+JJBarButtonItem.h"

#define kDefaultColor     ([UIColor whiteColor])
#define  kLeftTitleFont    (17.0)
#define  kRightTitleFont   (17.0)

@implementation UIBarButtonItem (JJBarButtonItem)

+ (UIBarButtonItem *)jjLeftItem:(id)target
                        selector:(SEL)selector
                     imageNormal:(UIImage *)imageNormal
               imageHightlighted:(UIImage *)imageHightlighted
                titleColorNormal:(UIColor *)titleColorNormal
          titleColorHightlighted:(UIColor *)titleColorHightlighted
                           title:(NSString *)title
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.backgroundColor = [UIColor clearColor];
    [btn setImage:imageNormal forState:UIControlStateNormal];
    [btn setImage:imageHightlighted?:imageNormal forState:UIControlStateHighlighted];
    [btn setTitleColor:titleColorNormal forState:UIControlStateNormal];
    [btn setTitleColor:titleColorHightlighted?:titleColorNormal forState:UIControlStateHighlighted];
    [btn setTitle:title forState:UIControlStateNormal];
    btn.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    btn.titleLabel.font = [UIFont systemFontOfSize:kLeftTitleFont];
    
    // 导航栏高度
    CGFloat fNaviBarHeight = 44.0;
    
    // 图片宽度
    CGFloat fImageWidth = 0.0;
    if (imageNormal) {
        fImageWidth = imageNormal.size.width;
    }
    
    // 文本宽度
    CGFloat fTitleWidth = 0.0;
    if (title.length > 0) {
        fTitleWidth = [self jjBoundingSizeWithLabel:btn.titleLabel size:CGSizeMake([UIScreen mainScreen].bounds.size.width, fNaviBarHeight)].width;
    }
    
    // 图片、文本间隔
    CGFloat fImageAndTitleEdge = 5.0;
    CGFloat fMaxWidth = fminf(fImageWidth + fTitleWidth + fImageAndTitleEdge, [UIScreen mainScreen].bounds.size.width * 0.3);
    btn.frame = CGRectMake(0.0, 0.0, fMaxWidth, fNaviBarHeight);
    
    // 文本偏移
    CGFloat fLeftEdgeInsets = 5.0;
    if (fTitleWidth > 0.0) {
        btn.titleEdgeInsets = UIEdgeInsetsMake(0.0, -fLeftEdgeInsets, 0.0, fMaxWidth + fLeftEdgeInsets - fTitleWidth);
    }
    
    // 图片偏移
    if (fImageWidth > 0.0) {
        btn.imageEdgeInsets = UIEdgeInsetsMake(0.0, -fLeftEdgeInsets, 0.0, fMaxWidth + fLeftEdgeInsets - fImageWidth);
        btn.titleEdgeInsets = UIEdgeInsetsMake(0.0, fImageAndTitleEdge - fLeftEdgeInsets, 0.0, fLeftEdgeInsets);
    }
    
    btn.exclusiveTouch = YES;
    [btn addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:btn];
    return item;
}

+ (UIBarButtonItem *)jjRightItem:(id)target
                         selector:(SEL)selector
                      imageNormal:(UIImage *)imageNormal
                imageHightlighted:(UIImage *)imageHightlighted
                    imageDisabled:(UIImage *)imageDisabled
                 titleColorNormal:(UIColor *)titleColorNormal
           titleColorHightlighted:(UIColor *)titleColorHightlighted
               titleColorDisabled:(UIColor *)titleColorDisabled
                            title:(NSString *)title
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.backgroundColor = [UIColor clearColor];
    [btn setImage:imageNormal forState:UIControlStateNormal];
    [btn setImage:imageHightlighted?:imageNormal forState:UIControlStateHighlighted];
    [btn setImage:imageDisabled?:imageNormal forState:UIControlStateDisabled];
    [btn setTitleColor:titleColorNormal forState:UIControlStateNormal];
    [btn setTitleColor:titleColorHightlighted?:titleColorNormal forState:UIControlStateHighlighted];
    [btn setTitleColor:titleColorDisabled?:titleColorNormal forState:UIControlStateDisabled];
    [btn setTitle:title forState:UIControlStateNormal];
    btn.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    btn.titleLabel.font = [UIFont systemFontOfSize:kRightTitleFont];
    
    // 导航栏高度
    CGFloat fNaviBarHeight = 44.0;
    
    // 图片宽度
    CGFloat fImageWidth = 0.0;
    if (imageNormal) {
        fImageWidth = imageNormal.size.width;
    }
    
    // 文本宽度
    CGFloat fTitleWidth = 0.0;
    if (title.length > 0) {
        fTitleWidth = [self jjBoundingSizeWithLabel:btn.titleLabel size:CGSizeMake([UIScreen mainScreen].bounds.size.width, fNaviBarHeight)].width;
    }
    
    // 图片、文本间隔
    CGFloat fImageAndTitleEdge = 5.0;
    CGFloat fMaxWidth = fminf(fmaxf(fImageWidth + fTitleWidth + fImageAndTitleEdge, 44.0), [UIScreen mainScreen].bounds.size.width * 0.3);
    btn.frame = CGRectMake(0.0, 0.0, fMaxWidth, fNaviBarHeight);
    
    // 图片偏移
    CGFloat fRightEdgeInsets = 2.0;
    if (fImageWidth > 0.0) {
        btn.imageEdgeInsets = UIEdgeInsetsMake(0.0, fMaxWidth + fRightEdgeInsets - fImageWidth, 0.0, -fRightEdgeInsets);
    }
    
    // 文本偏移
    if (fTitleWidth > 0.0) {
        btn.imageEdgeInsets = UIEdgeInsetsZero;
        btn.titleEdgeInsets = UIEdgeInsetsMake(0.0, fRightEdgeInsets + fImageAndTitleEdge, 0.0, -fRightEdgeInsets);
    }
    
    btn.exclusiveTouch = YES;
    [btn addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:btn];
    return item;
}

+ (UIBarButtonItem *)jjDefaultBackItem:(id)target
                               selector:(SEL)selector
                                  title:(NSString *)title
{
    return [UIBarButtonItem jjLeftItem:target
                               selector:selector
                            imageNormal:[UIImage imageNamed:@"default_back_normal"]
                      imageHightlighted:[UIImage imageNamed:@"default_back_hightlighted"]
                       titleColorNormal:[self jjColorWithHexString:@"#3e3e3e" alpha:1.0]
                 titleColorHightlighted:[self jjColorWithHexString:@"#858585" alpha:1.0]
                                  title:title];
}

+ (UIBarButtonItem *)jjDefaultBackItem:(id)target
                               selector:(SEL)selector
                       titleColorNormal:(UIColor *)titleColorNormal
                 titleColorHightlighted:(UIColor *)titleColorHightlighted
                                  title:(NSString *)title
{
    return [UIBarButtonItem jjLeftItem:target
                               selector:selector
                            imageNormal:[UIImage imageNamed:@"default_back_normal"]
                      imageHightlighted:[UIImage imageNamed:@"default_back_hightlighted"]
                       titleColorNormal:titleColorNormal
                 titleColorHightlighted:titleColorHightlighted
                                  title:title];
}

+ (UIBarButtonItem *)jjDefaultRightTitleItem:(id)target
                                     selector:(SEL)selector
                                        title:(NSString *)title
{
    return [UIBarButtonItem jjRightItem:target
                                selector:selector
                             imageNormal:nil
                       imageHightlighted:nil
                           imageDisabled:nil
                        titleColorNormal:[self jjColorWithHexString:@"#3e3e3e" alpha:1.0]
                  titleColorHightlighted:[self jjColorWithHexString:@"#858585" alpha:1.0]
                      titleColorDisabled:nil
                                   title:title];
}

+ (UIBarButtonItem *)jjDefaultRightItem:(id)target
                                selector:(SEL)selector
                        titleColorNormal:(UIColor *)titleColorNormal
                  titleColorHightlighted:(UIColor *)titleColorHightlighted
                      titleColorDisabled:(UIColor *)titleColorDisabled
                                   title:(NSString *)title
{
    return [UIBarButtonItem jjRightItem:target
                                selector:selector
                             imageNormal:nil
                       imageHightlighted:nil
                           imageDisabled:nil
                        titleColorNormal:titleColorNormal
                  titleColorHightlighted:titleColorHightlighted
                      titleColorDisabled:titleColorDisabled
                                   title:title];
}

+ (UIBarButtonItem *)jjDefaultRightImageItem:(id)target
                                     selector:(SEL)selector
                                  imageNormal:(UIImage *)imageNormal
                            imageHightlighted:(UIImage *)imageHightlighted
                                imageDisabled:(UIImage *)imageDisabled
{
    return [UIBarButtonItem jjRightItem:target
                                selector:selector
                             imageNormal:imageNormal
                       imageHightlighted:imageHightlighted
                           imageDisabled:imageDisabled
                        titleColorNormal:nil
                  titleColorHightlighted:nil
                      titleColorDisabled:nil
                                   title:nil];
}

- (UIButton *)jjContentViewButton
{
    if ([self.customView isKindOfClass:[UIButton class]]) {
        return (UIButton *)(self.customView);
    }
    
    return nil;
}

/**
 *   该函数的功能返回给定label字符串占的size
 *   @param label :字符串的label
 *   @param size :字符串占的size
 */
+ (CGSize)jjBoundingSizeWithLabel:(UILabel *)label size:(CGSize)size
{
    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin;
    options |= NSStringDrawingUsesFontLeading;
    options |= NSStringDrawingTruncatesLastVisibleLine;
    CGRect rect = [label.text boundingRectWithSize:size
                                     options:options
                                  attributes:@{NSFontAttributeName:label.font}
                                     context:nil];
    // 加两个像素, 防止emoji被切掉
    return CGSizeMake(ceilf(rect.size.width) + 1.0, ceilf(rect.size.height) + 2.0);
}

/**
 *   该函数的功能就是根据给的十六进制数和透明度返回对应的颜色值
 *   @param stringToConvert :十六进制字符串
 *   @param alpha :透明度
 */
+ (UIColor *)jjColorWithHexString:(NSString *)stringToConvert alpha:(CGFloat)alpha
{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    if ([cString length] < 6) {
        return kDefaultColor;
    }
    
    if ([cString hasPrefix:@"#"]) {
        cString = [cString substringFromIndex:1];
    }
    
    if ([cString length] != 6) {
        return kDefaultColor;
    }
    
    NSRange range = NSMakeRange(0, 2);
    NSString *rString = [cString substringWithRange:range];
    
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    unsigned int red = 0, green = 0, blue = 0;
    if ([[NSScanner scannerWithString:rString] scanHexInt:&red] &&
        [[NSScanner scannerWithString:gString] scanHexInt:&green] &&
        [[NSScanner scannerWithString:bString] scanHexInt:&blue]) {
        return [UIColor colorWithRed:((float)red / 255.0f)
                               green:((float)green / 255.0f)
                                blue:((float)blue / 255.0f)
                               alpha:alpha];
    }
    
    return kDefaultColor;
}

@end

别的就不多说了,代码就这么多。


框架验证

下面就验证下框架的使用,我们先写个类调用下试试。

1. JJNavigationVC.m
#import "JJNavigationVC.h"
#import "UIBarButtonItem+JJBarButtonItem.h"

@interface JJNavigationVC ()

@end

@implementation JJNavigationVC

#pragma mark - Override Base Function

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = @"无题";
    self.view.backgroundColor = [UIColor lightGrayColor];
    
    //左边item
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem jjLeftItem:self
                                                               selector:@selector(backButtonDidClick)
                                                            imageNormal:[UIImage imageNamed:@"my_sezhi1"]
                                                      imageHightlighted:[UIImage imageNamed:@"my_sezhi1"]
                                                       titleColorNormal:[UIColor blueColor]
                                                 titleColorHightlighted:[UIColor redColor]
                                                                  title:@"返回"
                                             ];
    
    //右边的item
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem jjRightItem:self
                                                                 selector:@selector(collectionButtonDidClick)
                                                              imageNormal:[UIImage imageNamed:@"my_shoucang1"]
                                                        imageHightlighted:[UIImage imageNamed:@"my_shoucang1"]
                                                            imageDisabled:[UIImage imageNamed:@"my_shoucang1"]
                                                         titleColorNormal:[UIColor blueColor]
                                                   titleColorHightlighted:[UIColor redColor]
                                                       titleColorDisabled:[UIColor blackColor]
                                                                    title:@"收藏"
                                              ];
}

#pragma mark - Action && Notification

- (void)backButtonDidClick
{
    NSLog(@"返回按钮");
}

- (void)collectionButtonDidClick
{
    NSLog(@"收藏按钮");
}

@end

下面我们看一下效果展示。

效果展示

这里文字大小我设置的是17号字体,里面定义的宏,想修改的直接修改宏就可以了。

#define  kLeftTitleFont    (17.0)
#define  kRightTitleFont   (17.0)

后记

希望我写的这个小框架能对大家有所帮助,谢谢大家的关注~~,继续努力。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,616评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,020评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,078评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,040评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,154评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,265评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,298评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,072评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,491评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,795评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,970评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,654评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,272评论 3 318
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,985评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,223评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,815评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,852评论 2 351

推荐阅读更多精彩内容