Does any know what I’ve done wrong here?
Problem
When I tap on the text field and the keyboard appears. Tap on the navgation link to get to the second screen. Then go back, the text field has not returned to the "non-focused" position.
- iOS: 16
- Sim: iPhone 14 Pro
Expectation
I am expecting to see the text field back at its original starting place. That is, when I tap the field, the keyboard avoidance causes that field to move up. Then I tap return on the keyboard to dismiss the keyboard, the text field returns to its starting position. When I navigation between view, I expect the same behaviour because the keyboard has been dismissed.
Steps
- Tap the textField (assuming software keyboard is on)
- Tap the navigationLink
- Tap Back
import SwiftUI
struct ContentView: View {
@State private var text: String = "Hello, world!"
var body: some View {
NavigationView {
VStack {
NavigationLink("Hello", destination: { Text("World") })
TextField("Whoops", text: $text)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
2
Answers
Try hide keyboard first and then navigate to the destination as following : –
You should change the focus of your textField before pushing another View. Since iOS 15 we can user @FocusState which does exactly that:
As for the Still view you can try implementing
.ignoresSafeArea(.keyboard)