Search code examples
swiftcolorsswiftuiuicolor

UINavigationBar foregroundColor use Color instead of UIColor


How do I use a Color instead of a UIColor for my navigation bar text?

Example, this works:

init() {
    UINavigationBar.appearance().largeTitleTextAttributes = [
        .foregroundColor: UIColor.red
    ]
}

This does not:

init() {
    UINavigationBar.appearance().largeTitleTextAttributes = [
        .foregroundColor: .red
    ]
}

How do I do this properly? UIColor.red is much uglier than Color.red


Solution

  • var largeTitleTextAttributes: [NSAttributedString.Key : Any]? { get set }
    

    As you can see the dictionary is [NSAttributedString.Key : Any], this means that .red cannot be inferred by the compiler, which is why you have to do, UIColor.red.

    The .foregroundColor works just fine because it is expecting a NSAttributedString.Key.

    I am afraid to say that you have to be explicit in this situation.