您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

改不動 navigationBar 背景色?用 Category 加一個 overlay 解決

編輯:iOS 開發綜合

在 iOS 開發中我們常需要客製 UINavigationBar 的底色。直覺會寫:

[self.navigationController.navigationBar setBackgroundColor:[UIColor redColor]];

但執行結果往往不如預期——顏色沒變,或只在中間一條變色。原因在於 UINavigationBar 的背景是由多層視圖(含 _UINavigationBarBackground 之類的私有視圖)構成的,直接設定 backgroundColor 會被上層遮蓋。

解法:自己插一層 overlay 墊在最底

思路是:先把系統自帶的背景圖與陰影圖清空,再插入一個自己的 UIView 到視圖層級的最底部,實際的顏色畫在這層上面。用 objc_getAssociatedObject 把這個 overlay 關聯到 bar 上,就能寫成一個乾淨的 Category。

宣告

@interface UINavigationBar (BackgroundColor)

// 設定 navigationBar 的背景顏色
- (void)lt_setBackgroundColor:(UIColor *)backgroundColor;

@end

實作

#import <objc/runtime.h>

@implementation UINavigationBar (BackgroundColor)

static char overlayKey;

- (UIView *)overlay {
    return objc_getAssociatedObject(self, &overlayKey);
}

- (void)setOverlay:(UIView *)overlay {
    objc_setAssociatedObject(self, &overlayKey, overlay, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void)lt_setBackgroundColor:(UIColor *)backgroundColor {
    if (!self.overlay) {
        // 把系統背景與分隔線換成空圖,避免遮住我們的顏色
        [self setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
        [self setShadowImage:[UIImage new]];

        self.overlay = [[UIView alloc] initWithFrame:CGRectMake(0, -20,
                                                                [UIScreen mainScreen].bounds.size.width, 64)];
        [self insertSubview:self.overlay atIndex:0];    // 墊到最底層
    }
    self.overlay.backgroundColor = backgroundColor;
}

@end

使用方式

[self.navigationController.navigationBar lt_setBackgroundColor:[UIColor redColor]];

幾個必須留意的細節

别忘了引入 runtime 頭文件

objc_getAssociatedObject 與 objc_setAssociatedObject 需要 #import <objc/runtime.h>,少了它就會出現未宣告的編譯錯誤。

硬編碼的 frame 是個隱憂

範例中 (0, -20, width, 64) 是「狀態列 20pt + 導航列 44pt」的舊尺寸。在瀏海機型與不同狀態列高度下,這組數字會失準。較穩健的做法是用 Auto Layout 把 overlay 的上下左右約束到 navigationBar,再透過 topAnchor 往上延伸狀態列的高度。

Category 中新增屬性要小心記憶體管理策略

Category 無法直接合成 ivar,所以必須靠關聯物件。這裡用 OBJC_ASSOCIATION_RETAIN_NONATOMIC 相當於 strong,對 UIView 物件是正確的;若換成 block 或 delegate,則要改用 COPY 或 ASSIGN,否則容易出現循環引用或懸垂指標。

iOS 15 之後的替代做法

系統後續提供了更直接的 API,若你的專案 Deployment Target 允許,優先使用官方方式會更省事:

// iOS 13 起
UINavigationBarAppearance *appearance = [[UINavigationBarAppearance alloc] init];
[appearance configureWithOpaqueBackground];
appearance.backgroundColor = [UIColor redColor];
appearance.shadowColor = [UIColor clearColor];      // 不要分隔線就設透明

self.navigationController.navigationBar.standardAppearance = appearance;
self.navigationController.navigationBar.scrollEdgeAppearance  = appearance;

這組 API 能正確處理狀態列、瀏海與 various 尺寸,也不需要自己維護 overlay,是目前的首選。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved