首页 > 解决方案 > 更改 TitleTextAttributes 文本颜色取决于导航栏颜色

问题描述

我有两个具有不同导航栏颜色的控制器。假设我想用导航栏黑色和 TitleTextAttributes 颜色 whiteColor 设置第一个控制器,然后导航到第二个控制器,它会更改导航栏白色和 TitleTextAttributes 黑色。导航栏颜色改变但标题文本属性没有改变。请建议。

我编写了这段代码并在 viewWillAppear 方法中使用。

内部导航栏类别

typedef NS_ENUM( NSUInteger, UINavigationBarColor) {
    White,
    Black
};

+(void)setNavigationColor:(UINavigationBarColor)color{
    if (color == White) {
         [[self appearance] setTintColor:[UIColor whiteColor]];
        NSDictionary *attributes = @{NSForegroundColorAttributeName:[UIColor blackColor]};
        [[self appearance] setTitleTextAttributes:attributes];
    } else {
        [[self appearance] setTintColor:[UIColor blackColor]];
        NSDictionary *attributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
        [[self appearance] setTitleTextAttributes:attributes];
    }
}

标签: iosuinavigationbar

解决方案


您的代码正在设置tintColorand titleTextAttributeson UINavgiationBar appearance。这只影响新创建的导航栏。它不会更改任何现有的导航栏。

您需要创建setNavigationColor一个实例方法并更改[self appearance]为 just self


推荐阅读