如何将 FocusState 变量传递给其他视图并允许这些视图更新该变量?[迅速]

Ass*_*bin 1 swift

目前,我有类似以下内容:

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>'
        })
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

好像我可以focusedField毫无问题地传递下去,但无法更新其值。怎么解决这个问题呢?

Ric*_*zio 9

为了保持一致性,也许最好使用属性包装器@FocusedState.Binding

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")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这允许做focusedField = true而不是focusedField.wrappedValue = true