本文章寫來紀(jì)念我在做IOS項目時遇到的導(dǎo)航欄之坑所刀。
為了方便調(diào)用,在自定義的NavigationController中添加屬性:
#import <UIKit/UIKit.h>
@interface ETNavigationController : UINavigationController
@property(nonatomic, strong) UIColor* foregroundColor;
//帶有alpha值的背景色
@property(nonatomic, strong) UIColor* backgroundColor;
@end
實現(xiàn)自定義訪問器:
-(UIColor *)foregroundColor
{
return self.navigationBar.tintColor;
}
-(void)setForegroundColor:(UIColor *)foregroundColor
{
self.navigationBar.tintColor = foregroundColor;
}
-(void)setBackgroundColor:(UIColor *)backgroundColor
{
_backgroundColor = backgroundColor;
//這是一個自定義UIImage分類中通過顏色來生成圖片的函數(shù)
UIImage* img = [UIImage imageWithColor:backgroundColor];
[self.navigationBar setBackgroundImage:img forBarMetrics:UIBarMetricsDefault];
CGFloat alpha;
[backgroundColor getRed:nil green:nil blue:nil alpha:&alpha];
BOOL translucent = (alpha < 1);
self.navigationBar.translucent = translucent;
}
到這已經(jīng)可以滿足設(shè)置一般的導(dǎo)航欄顏色的需求~~~,像QQ和淘寶那種下拉變換的導(dǎo)航欄目前沒做研究。
還有一點小技巧
如果需要切換頁面時對導(dǎo)航欄做(不透明<-->透明)變換,最好在變換的ViewController中做如下設(shè)置:
self.extendedLayoutIncludesOpaqueBars = YES;
這個屬性挎袜,我理解的意思是”使用extendedLayout的情況下,在導(dǎo)航欄不透明時也要把視圖延伸到navigationBar下方(將本控制器的view的頂點放在屏幕最上方)“沼撕,這樣視圖的頂部會被不透明的bar完全遮蓋宋雏。這個理解有點片面,因為只考慮了頂部的navigationBar务豺,實際上如果在底部有toolBar磨总,視圖也會延伸到toolBar的下面。
還有一個相關(guān)的屬性:
edgesForExtendedLayout
它決定了視圖布局時在哪些方向上面延伸笼沥,默認(rèn)是所有方向都延伸蚪燕。