Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a property to its default value explicitly in SwiftUI

Tags:

swift

swiftui

struct ContentView: View {
    @State private var isRed = false
    
    var body: some View {
        Button("Click Me") {
            isRed.toggle()
        }
        .foregroundColor(isRed ? .red : /* some code */)
    }
}

Is there a way to apply the following logic:

If isRed is true then apply the color red, else revert back to the default value for this property or the inherited value if there is one.

In other words are there keywords in SwiftUI similar to initial and inherit in CSS?

like image 258
Michael Knightly Avatar asked Sep 20 '25 13:09

Michael Knightly


2 Answers

As already mentioned in the comments many APIs accept nil for default / no change

struct ContentView: View {
    @State private var isRed = false
    
    var body: some View {
        Button("Click Me") {
            isRed.toggle()
        }
        .foregroundColor(isRed ? .red : nil)
    }
}

This works even if you specify a different tint color

struct ContentView: View {
    @State private var isRed = false
    
    var body: some View {
        Button("Click Me") {
            isRed.toggle()
        }
        .foregroundColor(isRed ? .red : nil)
        .tint(.yellow)
    }
   
}
like image 184
vadian Avatar answered Sep 23 '25 05:09

vadian


The default color for the buttons is the "accent color". You can use it in the modifier.

struct ContentView: View {
    @State private var isRed = false

    Button("Click Me") {
        isRed.toggle()
    }
    .foregroundColor(isRed ? .red : .accentColor)
}
like image 45
mucahid-erdogan Avatar answered Sep 23 '25 06:09

mucahid-erdogan