分离 UIAppearence 代码 [英] Separating UIAppearence code
问题描述
我想为我正在创建的应用程序添加主题.只需在 2 种颜色之间切换,我希望导航栏、工具栏等以所选颜色显示.
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.
当应用首次加载时,我在 AppDelegate 的 didFinishLaunchingWithOptions
方法中应用一种颜色.
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]];
}
假设默认主题是粉红色.我从分段控件切换到蓝色并推送到下一个视图控制器,那里还有一个 UIToolBar
.新选择的颜色(蓝色)仅应用于 UIToolBar
而不是 UINavigationBar
.
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?
谢谢.
推荐答案
您遇到的问题是由于UIAppearance
仅在下一次生效创建了一个 UI 控件.你的新 UIToolbar
呈现出新的外观,因为当你推送一个新的视图控制器时,它有一个全新的工具栏.你的 UINavigationBar
没有改变,因为它是在你的导航控制器视图创建时创建的,不会更新它的外观.
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.
您还必须直接在您的 navigationController 的 navigationBar 上更新该属性.例如:
You'll have to also update the property directly on your navigationController's navigationBar. e.g.:
self.navigationController.navigationBar.barTintColor = blueTheme;
这篇关于分离 UIAppearence 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!