Home > front end >  Set a property to its default value explicitly in SwiftUI
Set a property to its default value explicitly in SwiftUI

Time:12-30

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?

CodePudding user response:

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)
}

CodePudding user response:

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)
    }
   
}
  • Related