I have a SwiftUI view with multiple TextFields and a @FocusState bound to my view model. I want the first field to automatically get focus whenever the view appears(when coming back from a SecondView). Here’s a minimal example:
import SwiftUI import Combine
class MyViewModel: ObservableObject {
enum Field: Hashable {
case field1
case field2
case field3
}
@Published var field1: String = ""
@Published var field2: String = ""
@Published var field3: String = ""
@Published var focusedField: Field? = nil
}
struct ContentView: View {
@StateObject private var viewModel: MyViewModel
@FocusState private var activeField: MyViewModel.Field?
init(viewModel: MyViewModel) {
self._viewModel = StateObject(wrappedValue: viewModel)
}
var body: some View {
NavigationStack {
VStack(spacing: 20) {
TextField("Field 1", text: $viewModel.field1)
.focused($activeField, equals: .field1)
.textFieldStyle(.roundedBorder)
TextField("Field 2", text: $viewModel.field2)
.focused($activeField, equals: .field2)
.textFieldStyle(.roundedBorder)
TextField("Field 3", text: $viewModel.field3)
.focused($activeField, equals: .field3)
.textFieldStyle(.roundedBorder)
NavigationLink("Go to Second View") {
SecondView()
}
.padding(.top, 40)
}
.padding()
.onAppear {
// Attempt to focus the first field
viewModel.focusedField = .field1
activeField = viewModel.focusedField
}
.onChange(of: activeField) { _, newValue in
viewModel.focusedField = newValue
}
.onChange(of: viewModel.focusedField) { _, newValue in
activeField = newValue
}
}
}
}
struct SecondView: View {
var body: some View {
VStack {
Text("Second View")
.font(.title)
Text("Go back to see focus issue")
.padding()
}
}
}
What am I doing wrong?
.onDisappeartoSecondView()?SecondViewjust to solve thing in a first view @BenzyNeez