Search code examples
swiftxcodeswiftuiswift5xcode11

SwiftUI how to get dynamic color?


I have a config file and I want to change colors there. But in my view function background(bg1Color) gives me error;

Argument type 'UIColor' does not conform to expected type 'View'

How can I fix this?

My config file;

import UIKit
import Foundation

// Backgrounds
var bg1Color: UIColor = .black

My function codes;

.background(bg1Color) // HERE
.cornerRadius(10)

Solution

  • .background modifier takes a View and unlike SwiftUI's Color, UIKit's UIColor is not conformed to View protocol (by default).

    So you need to create a Color from your UIColor and then pass it to the .background modifier.

    .background(Color(bg1Color))
    

    or directly:

    .background(Color(.black))
    

    Very Important Note!

    UIColor and Color predefined named colors are not the same! And they have different shades!

    Example

    So you should NOT just replace UIColor with Color.

    Actually SwiftIUI.Color.red quals to UIKit.UIClor.systemRed