SwiftUI - Mutable @FocusState for child view?

I have a parent view with a @FocusState variable that I want to pass into a child view that contains a TextField. I want to be able to change the FocusState from within the child view, but I get the errors Cannot assign to property: 'self' is immutable and Cannot assign value of type 'Bool' to type 'FocusState<Bool>.Binding'.

Parent view:

struct ParentView: View {
    @State private var text: String
    @FocusState private var isEditing: Bool
    
    var body: some View {
        ChildView($text, $isEditing)
    }
}

struct ChildView: View {
    @Binding var text: String
    var isEditing: FocusState<Bool>.Binding
    
    init(_ text: Binding<String>, _ isEditing: FocusState<Bool>.Binding) {
        self._text = text
        self.isEditing = isEditing
    }
    
    var body: some View {
        TextField("Username", text: $text)
            .focused(isEditing)
        
        Button("Click me!") {
            isEditing = false  // Error here
        }
    }
}

Thanks so much!

1 answer

  • answered 2021-10-23 04:42 Asperi

    Just assign via binding to wrapped value, like

    Button("Click me!") {
        isEditing.wrappedValue = false  // << here !!
    }
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum