I'm using view models for my SwiftUI app and would like to have the focus state also in the view model as the form is quite complex.
This implementation using @FocusState in the view is working as expected, but not want I want:
import Combine
import SwiftUI
struct ContentView: View {
@ObservedObject private var viewModel = ViewModel()
@FocusState private var hasFocus: Bool
var body: some View {
Form {
TextField("Text", text: $viewModel.textField)
.focused($hasFocus)
Button("Set Focus") {
hasFocus = true
}
}
}
}
class ViewModel: ObservableObject {
@Published var textField: String = ""
}
How can I put the @FocusState into the view model?