iOS開發中全局修改UINavigationBar的樣式
本文主要介紹在開發中, 我們遇到需要修改UINavigationBar樣式的時候, 一種全局的修改方式, 而且非常高效, 適用, 希望對大家有幫助.
前言
在iOS開發中, 我們會經常跟UINavigationController打交道, 那麼修改UINavigationBar樣式的事情也是經常遇到的, 我之前的做法就是: 在每個childViewController中, 逐個修改樣式, 添加leftBarButtonItem 和 rightBarButtonItem等, 就像下面代碼這樣:
self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
self.navigationController.navigationBar.tintColor = [UIColor blackColor];
這樣的做法是非常低效的, 而且每個childController我們都需要設置, 如果我們需要自定義返回按鈕, 這樣的設置方式也是行不通的, 這種方式也會產生很多意想不到的問題, 相信使用過的朋友都有類似的經歷.
接下來, 介紹一種合理的設置方式:
全局設置
這種方法就是通過[UINavigationBar appearance]和[UIBarButtonItem appearance]來進行全局的設置, 下面貼出一段我設置的代碼:
[[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
[UINavigationBar appearance].titleTextAttributes = @{NSForegroundColorAttributeName : [UIColor whiteColor]};
[UINavigationBar appearance].backIndicatorImage =
[UINavigationBar appearance].backIndicatorTransitionMaskImage =
[UIImage templateImageNamed:@"nav_bar_back_icon_white"];
[[UINavigationBar appearance] setBarTintColor:MMA_BLACK(1)];
[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
// hide title of back button
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)
forBarMetrics:UIBarMetricsDefault];
NSShadow *clearShadow = [[NSShadow alloc] init];
clearShadow.shadowColor = [UIColor clearColor];
clearShadow.shadowOffset = CGSizeMake(0, 0);
UIColor *normalTitleColor = [UIColor whiteColor];
UIColor *highlightedTitleColor = [UIColor whiteColor];
[[UIBarButtonItem appearance] setTitleTextAttributes:@{
NSForegroundColorAttributeName : normalTitleColor,
NSShadowAttributeName : clearShadow
} forState:UIControlStateNormal];
[[UIBarButtonItem appearance] setTitleTextAttributes:@{
NSForegroundColorAttributeName : highlightedTitleColor,
NSShadowAttributeName : clearShadow
} forState:UIControlStateHighlighted];
[[UIBarButtonItem appearance] setTintColor:[UIColor whiteColor]];
[[UIToolbar appearance] setBarTintColor:[UIColor whiteColor]];
這個就需要我們在程序啓動的時候設置, 也就是在- (BOOL)application:(UIApplication )application didFinishLaunchingWithOptions:(NSDictionary )launchOptions 中設置, 這種設置方法的好處就是:
1.只需要設置一次, 不需要再每個childController中逐個設置
2.可以保證UINavigationBar的風格一致
3.通過這種方式可以自定義UINavigationController的返回鍵
總的來說, 建議大家通過這種方式設置, 這樣其實能夠很大程度上提高開發效率.
總結
建議大家講上述設置代碼, 寫進UINavigationBar的Category中, 這樣我們就可以實現複用, 這也是一種很好的編程習慣. 希望本文對在UINavigationBar樣式設置上遇到問題的同學有幫助.