将导航栏标题文本更改为自定义颜色?

时间:2020-11-10 05:44:13

标签: ios swift swiftui uikit

我正在尝试使用我的appDelegate中的以下代码将标题栏文本更改为自定义的薰衣草色

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor(red: 0.9069682956, green: 0.7839415669, blue: 0.9612388015, alpha: 1)]

    return true
}

但是标题栏文本仍显示为黑色。有没有更好的方法可以改变这一点?

1 个答案:

答案 0 :(得分:2)

可能为时过早,尝试添加init中的ContentView,并为大标题(SwiftUI NavigationView的默认设置)添加一些内容,例如

struct ContentView: View {

    init() {
        UINavigationBar.appearance().titleTextAttributes = 
            [NSAttributedString.Key.foregroundColor: 
               UIColor(red: 0.9069682956, green: 0.7839415669, blue: 0.9612388015, alpha: 1)]
        UINavigationBar.appearance().largeTitleTextAttributes = 
            [NSAttributedString.Key.foregroundColor: 
               UIColor(red: 0.9069682956, green: 0.7839415669, blue: 0.9612388015, alpha: 1)]
    }

    // ... other code with NavigationView here
}

通过Xcode 12.1 / iOS 14.1测试