ios - 分离 UIAppearence 代码

标签 ios themes uinavigationbar uicolor uiappearance

我想为我正在创建的应用程序添加主题。只需在 2 种颜色之间切换,我希望导航栏、工具栏等以所选颜色显示。

当应用首次加载时,我在 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]];

在第一个 View Controller 中,我放置了一个分段控件来切换颜色。

- (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 的 View Controller 。新选择的颜色(蓝色)仅应用于 UIToolBar,而不应用于 UINavigationBar

有没有更好的方法来解决这个问题?另外我想把与主题相关的代码放在一个单独的类中,因为它重复了很多代码。我该怎么做?

谢谢。

最佳答案

您遇到的问题是因为 UIAppearance 仅在 下一次 创建 UI 控件时生效。你的新 UIToolbar 呈现出新的外观,因为当你按下一个新的 View Controller 时,它有一个全新的工具栏。您的 UINavigationBar 没有改变,因为它是在创建导航 Controller 的 View 时创建的,并且不会更新其外观。

您还必须直接更新 navigationController 的导航栏上的属性。例如:

self.navigationController.navigationBar.barTintColor = blueTheme;

关于ios - 分离 UIAppearence 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21317410/

相关文章:

ios - 自定义 UIToolbar,Apple 允许什么?

ios - 在日期选择器 IOS 中设置特定日期

ios - 如何从Fabric Answers仪表板中删除自定义事件?

css - Oracle Apex 应用程序中的显示错误

php - WordPress 视觉编辑器未加载

ios - rightBarButtonItem 出现在 NavigationBar 的中央

ios - Objective-C:设置 bool 值时遇到问题?

php - Yii 主题不工作

html - 以 Wordpress 为中心的导航

ios - 导航栏未正确显示(显示为 float 而不是固定栏)