2014-01-23 34 views
0

我想實現添加主題到我創建的應用程序。只需切換2種顏色,我希望導航欄,工具欄等以選定的顏色顯示。分離UIAppearence代碼

當應用第一次加載時,我在AppDelegate的didFinishLaunchingWithOptions方法中應用一種顏色。

UIColor *blueTheme = [UIColor colorWithRed:80/255.0f green:192/255.0f blue:224/255.0f alpha:1.0f]; 
UIColor *pinkTheme = [UIColor colorWithRed:225/255.0f green:87/255.0f blue:150/255.0f alpha:1.0f]; 

[[UINavigationBar appearance] setBarTintColor:pinkTheme]; 
[[UIToolbar appearance] setBarTintColor:pinkTheme]; 

[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]]; 

而在第一個視圖控制器,我已經把分段控制切換顏色。

- (IBAction)themeChosen:(UISegmentedControl *)sender 
{ 
    if (sender.selectedSegmentIndex == 0) { 
     UIColor *blueTheme = [UIColor colorWithRed:80/255.0f green:192/255.0f blue:224/255.0f alpha:1.0f]; 

     [[UINavigationBar appearance] setBarTintColor:blueTheme]; 
     [[UIToolbar appearance] setBarTintColor:blueTheme]; 
    } else { 
     UIColor *pinkTheme = [UIColor colorWithRed:225/255.0f green:87/255.0f blue:150/255.0f alpha:1.0f]; 

     [[UINavigationBar appearance] setBarTintColor:pinkTheme]; 
     [[UIToolbar appearance] setBarTintColor:pinkTheme]; 
    } 
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]]; 
} 

假設默認主題是粉色。我從分段控制切換到藍色,並推送到下一個視圖控制器,那裏也有UIToolBar。新選擇的顏色(藍色)僅適用於UIToolBar,但不適用於UINavigationBar

有沒有更好的方法來解決這個問題?此外,我想將與主題相關的代碼放在單獨的類中,因爲它重複了很多代碼。我怎麼做?

謝謝。

回答

3

您遇到的問題是由於UIAppearance僅在下一次生成UI控件時才生效。您的新UIToolbar呈現新外觀,因爲當您推新視圖控制器時,它具有全新的工具欄。您的UINavigationBar未更改,因爲它是在創建導航控制器的視圖時創建的,並且不會更新其外觀。

您還必須直接在navigationController的navigationBar上更新屬性。例如:

self.navigationController.navigationBar.barTintColor = blueTheme; 
+0

我明白了。我現在知道了。謝謝 :) – Isuru