Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The @FocusState property wrapper is used in SwiftUI to track the focused state of a view. It can be used in conjunction with view models to store and set the focus state of a particular view. Here is the process for utilizing @FocusState with view models:

  1. Declare a property in your view model that will store the focus state value.
@FocusState private var isFocused: Bool
  1. Add a binding to the view model property in your view.
TextField("Username", text: $username)
    .focused($viewModel.isFocused)
  1. Use the @FocusState property wrapper to set and retrieve the focused state of the view.
@FocusState private var isFocused: Bool

var body: some View {
    TextField("Username", text: $username)
        .focused($isFocused)
}
  1. You can then use the view model property to perform any necessary actions when the view gains or loses focus.
@FocusState private var isFocused: Bool

func onFocusChange() {
    if isFocused {
        // Perform some action when the view gains focus
    } else {
        // Perform some action when the view loses focus
    }
}

TextField("Username", text: $username)
    .onChange(of: isFocused) { isFocused in
        onFocusChange()
    }
    .focused($isFocused)