Skip to content

Color – SwiftUI

Color in SwiftUI is an environment-dependent color.

How to change the background color of the view in SwiftUI

This will set the background of the Text to .red

var body: some View {
    Text("Hello AppMakers.dev visitors")
        .background(Color.red)
}

If you want to set the whole screen to be red, you can do this. This will center the text and set the whole view to red.

var body: some View {
    HStack {
        Spacer()
        VStack {
            Spacer()
            Text("Hello AppMakers.dev")
            Spacer()
        }
        Spacer()
    }
    .background(Color.red)
}

Or use this instead to fill the whole view with red, ignoring the safe area.

var body: some View {
    ZStack {
        Color.red
            .edgesIgnoringSafeArea(.all)
        Text("Hello AppMakers.Dev")
    }
}

How to change Text Color in SwiftUI

This code will change the text color to green. Use `foregroundColor(_:)` to set the color that the view uses for foreground elements.

var body: some View {
    Text("Hello")
        .foregroundColor(Color.green)
}

How to convert UIColor to SwiftUI Color

To convert UIColor to SwiftUI Color, add this extension to your codebase.

extension UIColor {
    var suColor: Color { Color(self) }
}

After that, you can call `.suColor` on any `UIColor` instance to get a SwiftUI Color.

someUIColor.suColor

How to use Color set from Assets Catalog?

If you’ve created a color named “newColor” in your Assets catalog, you can use it like this:

Color("newColor")

To simplify usage of Asset Catalog colors, add this extension:

extension Color {
    static let newColor = Color("newColor")
    static let newColor2 = Color("newColor2")
}

Learn more about SwiftUI using SwiftUI Tutorials by AppMakers. You can always check the official documentation if updates occur.

Color Documentation

Back To Top
Search