在開發項目的時候,項目中使用的UINavigationController可能有很多,如何快速設置整個項目中的UINavigationBar的標題以及UINavigationBar上的按鈕的樣式呢?
設置UINavigationBar標題主題
// 設置UINavigationBar的主題,只要使用了該UINavigationController,都會被統一設置
UINavigationBar *bar = [UINavigationBar appearance];
// 設置整個項目中的導航欄背景圖片
// [bar setBackgroundImage:<#(nullable UIImage *)#> forBarPosition:<#(UIBarPosition)#> barMetrics:<#(UIBarMetrics)#>];// 與設備的橫豎屏有關
[bar setBackgroundImage:[UIImage imageNamed:@"navigationbar.png"] forBarMetrics:UIBarMetricsDefault];
// 設置UINavigationBar上的所有文字屬性
// 設置文字屬性
NSMutableDictionary *barTextAttrs = [NSMutableDictionary dictionary];
barTextAttrs[UITextAttributeTextColor] = [UIColor whiteColor];
// UITextAttributeFont --> NSFontAttributeName(iOS7)
#warning 過期 : 並不代表不能用, 僅僅是有最新的方案可以取代它
barTextAttrs[UITextAttributeFont] = [UIFont systemFontOfSize:21.0];
// UIOffsetZero是結構體, 只要包裝成NSValue對象, 才能放進字典\數組中
barTextAttrs[UITextAttributeTextShadowOffset] = [NSValue valueWithUIOffset:UIOffsetZero];
[bar setTitleTextAttributes:barTextAttrs];
設置UINavigationBar上的按鈕主題樣式
// 設置項目所有UIBarButtonItem的主題
// 通過appearance對象能修改整個項目中所有UIBarButtonItem的樣式
UIBarButtonItem *appearance = [UIBarButtonItem appearance];
/**設置文字屬性**/
// 設置普通狀態的文字屬性
NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
textAttrs[UITextAttributeTextColor] = [UIColor orangeColor];
textAttrs[UITextAttributeFont] = [UIFont systemFontOfSize:15];
textAttrs[UITextAttributeTextShadowOffset] = [NSValue valueWithUIOffset:UIOffsetZero];
[appearance setTitleTextAttributes:textAttrs forState:UIControlStateNormal];
// 設置高亮狀態的文字屬性
NSMutableDictionary *highTextAttrs = [NSMutableDictionary dictionaryWithDictionary:textAttrs];
highTextAttrs[UITextAttributeTextColor] = [UIColor blueColor];
[appearance setTitleTextAttributes:highTextAttrs forState:UIControlStateHighlighted];
// 設置不可用狀態(disable)的文字屬性
NSMutableDictionary *disableTextAttrs = [NSMutableDictionary dictionaryWithDictionary:textAttrs];
disableTextAttrs[UITextAttributeTextColor] = [UIColor lightGrayColor];
[appearance setTitleTextAttributes:disableTextAttrs forState:UIControlStateDisabled];
/**設置按鈕背景**/
// 技巧: 爲了讓某個按鈕的背景消失, 可以設置一張完全透明的背景圖片
[appearance setBackgroundImage:[UIImage imageNamed:@"navigationbar_button_background"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
如果設置了UIToolBar的鍵盤上有按鈕(UIBarButtonItem類型),UIBarButtonItem主題設置後,也會對UIToolBar的按鈕有效果,即該設置對項目中的所有UIBarButtonItem有效。