一種UINavigationBar的簡單封裝

版本記錄

版本號 時間
V1.0 2017.08.04

前言

??我們的app一般都需要導航欄,極個別的除外,比如說很多游戲是沒有導航欄的,但是絕大部分是都有的,不同的app都有自己特點的導航欄,有的是透明的,有的是某種顏色的,等等??傊?,我們做app不可避免的會碰到自定義導航欄的情況。這一個小框架主要就是對自定義導航欄進行了封裝,提供了幾種樣式,希望對大家有所幫助。

框架了解

??這個小框架主要就是實現(xiàn)了自定義導航欄的功能,并提供了四種樣式,有需要的可以直接把這個拖過去,如果有你需要的樣式直接調(diào)用就可以了,如果沒有只需要加一個枚舉成員,在實現(xiàn)以下類似功能就可以了,希望能給您提供幫助。


框架實現(xiàn)

下面我們就直接看代碼,看框架是如何實現(xiàn)的。

1. UINavigationBar+JJNavigationBar.h
#import <UIKit/UIKit.h>

extern NSString *const kJJNavigationBarDefaultTitleColor;
extern NSString *const kJJNavigationBarStyle4Color;

typedef NS_ENUM(NSInteger, JJUINavigationBarStyle) {
    JJUINavigationBarStyleDefault = 0,     // 白色背景, 帶底部線
    JJUINavigationBarStyleValue1,          // 白色背景
    JJUINavigationBarStyleValue2,          // 透明背景, title灰色
    JJUINavigationBarStyleValue3,          // 透明背景, title白色
    JJUINavigationBarStyleValue4,          // 灰色背景
};

@interface UINavigationBar (JJNavigationBar)

@property (nonatomic, assign, readonly) JJUINavigationBarStyle jjStyle;
@property (nonatomic, strong, readonly) UIView *jjViewBottomLine;

+ (void)jjSetDefaultSytle;

- (void)jjSetNavigationBarStyle:(JJUINavigationBarStyle)style;

- (void)jjSetBackgroundImageWithColor:(UIColor *)backgroundColor alpha:(float)alpha;

@end
2. UINavigationBar+JJNavigationBar.m
#import "UINavigationBar+JJNavigationBar.h"
#import <objc/runtime.h>

#define kJJNavigationBarFontSize   [UIFont systemFontOfSize:20.0]
#define kDefaultColor              ([UIColor whiteColor])

static char kJJNavigationBarBottomLineKey;
static char kJJNavigationBarStyleKey;

NSString *const kJJNavigationBarDefaultTitleColor = @"#3e3e3e";
NSString *const kJJNavigationBarStyle4Color = @"#f5f5f5";

@interface UINavigationBar ()

@property (nonatomic, assign) NSNumber *jjStyleObj;
@property (nonatomic, strong) UIView *jjViewBottomLine;

@end

@implementation UINavigationBar (JJNavigationBar)

#pragma mark - Get/Set Function

- (UIView *)jjViewBottomLine
{
    return objc_getAssociatedObject(self, &kJJNavigationBarBottomLineKey);
}

- (void)setJjViewBottomLine:(UIView *)newAldViewBottomLine
{
    objc_setAssociatedObject(self, &kJJNavigationBarBottomLineKey, newAldViewBottomLine, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSNumber *)jjStyleObj
{
    return objc_getAssociatedObject(self, &kJJNavigationBarStyleKey);
}

- (void)setJjStyleObj:(NSNumber *)newJjStyleObj
{
    objc_setAssociatedObject(self, &kJJNavigationBarStyleKey, newJjStyleObj, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (JJUINavigationBarStyle)aldStyle
{
    return self.jjStyleObj.intValue;
}

#pragma mark - Class Public Function

+ (void)jjSetDefaultSytle
{
    [UINavigationBar appearance].barTintColor = [UIColor whiteColor];
    [UINavigationBar appearance].barStyle = UIBarStyleDefault;
    [UINavigationBar appearance].translucent = NO;
    [UINavigationBar appearance].titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor],
                                                         NSFontAttributeName:[UIFont boldSystemFontOfSize:18.5]};
    [UINavigationBar appearance].tintColor = [UIColor whiteColor];
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16],NSFontAttributeName, nil];
    [[UIBarButtonItem appearance] setTitleTextAttributes:attributes forState:0];
}

#pragma mark - Object Private Function

- (void)jjRemoveBottom
{
    [self.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull objSub, NSUInteger idxSub, BOOL * _Nonnull stopSub) {
        if ([objSub isKindOfClass:NSClassFromString(@"_UIBarBackground")] ||
            [objSub isKindOfClass:NSClassFromString(@"_UINavigationBarBackground")]) {
            __block BOOL isFoundSystemBottomLine;
            [objSub.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull objSubBackground, NSUInteger idxSubBackground, BOOL * _Nonnull stopSubBackground) {
                if ([objSubBackground isKindOfClass:[UIImageView class]] &&
                    fabs(CGRectGetHeight(objSubBackground.bounds) - 1.0 / [UIScreen mainScreen].scale) < FLT_EPSILON) {
                    objSubBackground.hidden = YES;
                    isFoundSystemBottomLine = YES;
                    *stopSubBackground = YES;
                }
            }];
        }
    }];
}

- (void)jjSetupDefaultStyle
{
    if (!self.jjViewBottomLine) {
        [self jjRemoveBottom];
        
        self.jjViewBottomLine = [[UIView alloc] initWithFrame:CGRectMake(0.0, CGRectGetHeight(self.bounds) - 0.5, CGRectGetWidth(self.bounds), 0.5)];
        self.jjViewBottomLine.backgroundColor = [self jjColorWithHexString:@"e5e5e5" alpha:1.0];
        [self addSubview:self.jjViewBottomLine];
    }
    
    self.jjViewBottomLine.hidden = NO;
    self.titleTextAttributes = @{NSForegroundColorAttributeName:[self jjColorWithHexString:kJJNavigationBarDefaultTitleColor alpha:1.0],
                                 NSFontAttributeName:kJJNavigationBarFontSize};
    [self aldSetBackgroundImageWithColor:[UIColor whiteColor] alpha:1.0];
    self.translucent = NO;
}

- (void)jjSetupValue1
{
    [self jjRemoveBottom];
    self.jjViewBottomLine.hidden = YES;
    self.titleTextAttributes = @{NSForegroundColorAttributeName:[self jjColorWithHexString:kJJNavigationBarDefaultTitleColor alpha:1.0],
                                 NSFontAttributeName:kJJNavigationBarFontSize};
    [self aldSetBackgroundImageWithColor:[UIColor whiteColor] alpha:1.0];
    self.translucent = NO;
}

- (void)jjSetupValue2
{
    [self jjRemoveBottom];
    
    // 設置隱藏
    self.jjViewBottomLine.hidden = YES;
    self.titleTextAttributes = @{NSForegroundColorAttributeName:[self jjColorWithHexString:kJJNavigationBarDefaultTitleColor alpha:1.0],
                                 NSFontAttributeName:kJJNavigationBarFontSize};
    [self aldSetBackgroundImageWithColor:[UIColor clearColor] alpha:0.0];
    self.shadowImage = [UIImage new];
    self.translucent = YES;
}

- (void)jjSetupValue3
{
    [self jjRemoveBottom];
    
    // 設置隱藏
    self.jjViewBottomLine.hidden = YES;
    self.titleTextAttributes = @{NSForegroundColorAttributeName:[self jjColorWithHexString:@"#ffffff"  alpha:1.0],
                                 NSFontAttributeName:kJJNavigationBarFontSize};
    [self aldSetBackgroundImageWithColor:[UIColor clearColor] alpha:0.0];
    self.shadowImage = [UIImage new];
    self.translucent = YES;
}

- (void)jjSetupValue4
{
    [self jjRemoveBottom];
    
    // 設置隱藏
    self.jjViewBottomLine.hidden = YES;
    self.titleTextAttributes = @{NSForegroundColorAttributeName:[self jjColorWithHexString:kJJNavigationBarDefaultTitleColor alpha:1.0],
                                 NSFontAttributeName:kJJNavigationBarFontSize};
    [self aldSetBackgroundImageWithColor:[self jjColorWithHexString:kJJNavigationBarStyle4Color alpha:1.0] alpha:1.0];
    self.translucent = NO;
}

//根據(jù)顏色返回相應顏色填充的圖片

- (UIImage *)aldImageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0, 0.0, 1.0, 1.0);
    
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *imageColor = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return imageColor;
}

#pragma mark - Object Public Function

- (void)jjSetNavigationBarStyle:(JJUINavigationBarStyle)style
{
    self.jjStyleObj = [NSNumber numberWithInt:style];
    
    switch (style) {
        case JJUINavigationBarStyleDefault:
        {
            [self jjSetupDefaultStyle];
        }
            break;
            
        case JJUINavigationBarStyleValue1:
        {
            [self jjSetupValue1];
        }
            break;
            
        case JJUINavigationBarStyleValue2:
        {
            [self jjSetupValue2];
        }
            break;
            
        case JJUINavigationBarStyleValue3:
        {
            [self jjSetupValue3];
        }
            break;
            
        case JJUINavigationBarStyleValue4:
        {
            [self jjSetupValue4];
        }
            break;
            
        default:
        {
            [self jjSetupDefaultStyle];
        }
            break;
    }
}

- (void)aldSetBackgroundImageWithColor:(UIColor *)backgroundColor alpha:(float)alpha
{
    [self setBackgroundImage:[self aldImageWithColor:[backgroundColor colorWithAlphaComponent:alpha]] forBarMetrics:UIBarMetricsDefault];
}

#pragma mark - Class Public Function

/**
 *   該函數(shù)的功能就是根據(jù)給的十六進制數(shù)和透明度返回對應的顏色值
 *   @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

上面就是所有的代碼了。


框架驗證

下面我們就調(diào)用一下,看一下這個框架的效果。

1. JJNavigationVC.m
#import "JJNavigationVC.h"
#import "UIBarButtonItem+JJBarButtonItem.h"
#import "UINavigationBar+JJNavigationBar.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:@"收藏"
                                              ];
    
    //設置導航欄背景
    [self.navigationController.navigationBar jjSetNavigationBarStyle:JJUINavigationBarStyleValue2];
}

#pragma mark - Action && Notification

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

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

@end

下面就給出幾種導航欄樣式的效果示意圖。

default
value1
value2
value3

后記

希望能夠對大家有所幫助,歡迎指正其中的不足,謝謝~~~

院子
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • ?父母手中有根線,牽著兒女的一邊,線越來越遠,心就越來越懸;我們用青春在外恣意飛翔,他們用盡一生抬頭仰望,我們何時...
    BULABULA小八閱讀 250評論 0 1
  • 邀請所有的天使指導靈高級智慧們開啟我美好的一天 給到我這一天的最佳利益,讓我無限喜悅,無限豐盛,無限智慧,活在純?nèi)?..
    大吉大力_fd0f閱讀 350評論 0 0
  • 大學 一場沒有歸期的旅程 一場謝幕的表演 一場飄落的煙火 懷念大學 懷念四年青春 青春的不羈 青春的執(zhí)著 承載著夢...
    漫步文學世界閱讀 221評論 0 1
  • 很感謝上帝給了我這個禮物,很珍貴。 2月5號年初九,看著這個挺嶄新的禮物。挺開心的,我在這133天里,雖然開心的程...
    蘇素_Sophie閱讀 247評論 0 0
  • 103沉痛的真相 帝后沉浸在悲傷中,沉浸在對往事的追憶中。 “皇后若想懺悔,只怕不僅僅對我母妃一人而已?!蹦防溲?..
    凌漪閱讀 339評論 0 0

友情鏈接更多精彩內(nèi)容