Home > Blockchain >  How to pass a FocusState variable to other views and allow those views to update the variable? [Swif
How to pass a FocusState variable to other views and allow those views to update the variable? [Swif

Time:11-04

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?

CodePudding user response:

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
        }
        // ...
    }
}

CodePudding user response:

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

  • Related