问题
I want to implement add themes to an app I'm creating. Simply just switching between 2 colors and I want the navigation bars, tool bars etc. to appear in the selected color.
When the app first loads, I apply one color to in the didFinishLaunchingWithOptions
method in the AppDelegate.
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]];
And in the first view controller I have put a segmented control to switch the colors.
- (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]];
}
Say the default theme is pink. I switch to blue from the segmented control and push to the next view controller where there is a UIToolBar
as well. The newly chosen color(blue) is applied only to the UIToolBar
but not to the UINavigationBar
.
Is there a better way to go about this? Also I'd like to put the code related to themes in a separate class because it repeats a lot of code. How do I do that?
Thanks.
回答1:
The problem you're having is due to the fact that UIAppearance
only takes effect the next time a UI control is created. Your new UIToolbar
takes on the new appearance because when you push a new viewcontroller it has a brand new toolbar. Your UINavigationBar
is not changing, because it was created when your navigationcontroller's view was created, and won't update its appearance.
You'll have to also update the property directly on your navigationController's navigationBar. e.g.:
self.navigationController.navigationBar.barTintColor = blueTheme;
来源:https://stackoverflow.com/questions/21317410/separating-uiappearence-code