PipEvangelist
PipEvangelist

Reputation: 631

How to pass a FocusState variable to other views and allow those views to update the variable? [Swift]

Currently, I have something like the following:

struct ViewA: View {
    @FocusState private var focusedField: Bool
    var body: some View {
        ViewB(focusedField: $focusedField)
        // some other views that read focusedField...
    }
}


struct ViewB: View {
    @State var focusedField: FocusState<Bool>.Binding
    var body: some View {
        Button(action: {
            focusedField = true   // ERROR: Cannot assign value of type 'Bool' to type 'FocusState<Bool>'
        })
        // ...
    }
}

Seems like I can pass down focusedField with no problem but unable to update its value. How to solve this?

Upvotes: 2

Views: 2211

Answers (2)

Rico Crescenzio
Rico Crescenzio

Reputation: 4226

For consistency, maybe it's better to use the property wrapper @FocusedState.Binding instead.

struct ViewA: View {
    @FocusState private var focusedField: Bool
    var body: some View {
        ViewB(focusedField: $focusedField)
        // some other views that read focusedField...
    }
}

struct ViewB: View {
    @FocusState.Binding var focusedField: Bool
    var body: some View {
        Button(action: {
            focusedField = true
        }) {
            Text("Tap me")
        }
    }
}

This allows to do focusedField = true instead of focusedField.wrappedValue = true

Upvotes: 9

aheze
aheze

Reputation: 30248

Instead of directly setting focusedField, use the wrappedValue property.

struct ViewA: View {
    @FocusState private var focusedField: Bool
    var body: some View {
        ViewB(focusedField: $focusedField)
        // some other views that read focusedField...
    }
}


struct ViewB: View {
    var focusedField: FocusState<Bool>.Binding
    var body: some View {
        Button(action: {
            focusedField.wrappedValue = true /// assign `wrappedValue`
        }) {
            Text("Click me!") /// Side note: you need a label for the button too, otherwise your code won't compile
        }
        // ...
    }
}

Upvotes: 2

Related Questions