SwiftUI - @FocusState as condition

For some reason, I wish to use @FocusState as a condition, but it doesn't work.

struct ContentView: View {
    @FocusState private var mystate: Bool
    var body: some View {
        if mystate {
            Text("Hello")
        }

        Button(action: {
            print("before: \(mystate)")
            mystate.toggle()
            print("after: \(mystate)")
        }, label: {
            Text("Click Me")
        })
    }
}

And the console output is

before: false
after: false

Can anyone please explain why the mystate isn't changed when button get tapped? Thank you!


Solution 1:

So, the FocusState needs something to focus on, without it it just changes itself to false (that’s why I added TextField) - and, it doesn’t change right away, but after it focuses something, therefore delay is needed.

This works for me:


struct ContentView: View {
    @FocusState private var mystate: Bool
    var body: some View {
        if mystate {
            Text("Hello")
        }
        
        Button(action: {
            print("before: \(mystate)")
            mystate.toggle()
            DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(50)){
                print("after: \(mystate)")
            }
            
        }, label: {
            Text("Click Me")
        })
        TextField("myTextField", text: .constant("text")).focused($mystate)
    }
}