UINavigationBar修改背景顏色(2)

UINavigationController是常用的控件,經常會修改navigationBar的樣式,

一.設置navigationBar的背景顏色

首先:效果圖(設置navigationbar背景爲紅色)







上面效果對應的代碼如下:

在appdelegate中設置:

1️⃣

UINavigationBar *bar = [UINavigationBarappearance] ;

[bar setBarTintColor:[UIColorredColor]];//設置navigationBar的背景顏色(對應效果圖最外層紅色)

[bar setTitleTextAttributes:@{UITextAttributeTextColor : [UIColorblueColor]}];//設置字體顏色


在viewController中設置

2️⃣

self.navigationItem.title =@"呵呵呵噠";

self.navigationController.navigationBar.backgroundColor = [UIColor yellowColor];//也是設置背景顏色,(對應效果圖中內層黃色)

self.navigationController.navigationBar.barStyle = UIBarStyleDefault;


實際上1️⃣修改的是紅色箭頭對應的內容

2️⃣修改的是黃色箭頭對應的內容  只是紅色把黃色覆蓋了

  navigationBar



最後顯示爲紅色,所以結果顯而易見 想要改變navigationBar的背景色,只有用這種方法:

UINavigationBar *bar = [UINavigationBar appearance] ;

[bar setBarTintColor:[UIColor redColor]];


二.動態修改navigationBar的背景顏色,類似qq空間

首先想到的就是在滑動scrollView時動態修改背景顏色的透明度,或者修改背景顏色,但實際操作時發現不可行 

官方解釋:

Use the UIAppearance protocol to get the appearance proxy for a class. You can customize the appearance of instances of a class by sending appearance modification messages to the class’s appearance proxy.

iOS applies appearance changes when a view enters a window, it doesn’t change the appearance of a view that’s already in a window. To change the appearance of a view that’s currently in a window, remove the view from the view hierarchy and then put it back.

我的理解是:navigationBar已經創建成功,外觀經不再發生變化,除非重繪視圖(刪除背景視圖重新添加),否則外觀將不會發生變化。

解決辦法

1️⃣:隱藏navigationBar,自己重寫一個view代替navigationBar的功能

2️⃣:替換navigationBar:重寫一個naviagationBar繼承系統的navigationBar,在哪個紅色背景之上添加一個view,我們可以動態的改變該view顏色


考慮到繼承UINavigationBar使用起來會非常不便,我們決定用Category來實現,首先定義我們的category:

1
2
3
@interface UINavigationBar (BackgroundColor)
- (void)lt_setBackgroundColor:(UIColor *)backgroundColor;
@end

實現:我們使用associatedObject將overlayView動態地綁定到UINavigationBar的instance上,當調用lt_setBackgroundColor的時候,我們只要更新這個overlayView就行啦~

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@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]];        // insert an overlay into the view hierarchy
        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



自定義iOS7導航欄背景,標題和返回按鈕文字顏色

http://blog.csdn.net/mad1989/article/details/41516743











發佈了38 篇原創文章 · 獲贊 19 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章