Thanks for your clarification. Now I see the behavior you described.
To be very clear, I see on my iPhone as well that TextField
loses the focus when getting a Return
key from an external keyboard. This doesn't matter because people probably don't use an external keyboard with their iPhone, but the behavior is consistent on iOS and iPadOS, and is most likely as-designed.
To change the behavior, the only thing I can see is that you move the focus back to the text field in .onKeyPress
, as shown below:
struct MyForm: View {
enum Field: Hashable {
case name
}
@State private var name = ""
@FocusState private var focusedField: Field?
var body: some View {
Form {
TextField("Name", text: $name, axis: .vertical)
.lineLimit(2...4)
.focused($focusedField, equals: .name)
.onKeyPress(characters: .newlines, phases: .down) { keyPress in
Task {
try await Task.sleep(for: .seconds(0.2))
focusedField = .name
name += "\n"
}
return .handled
}
}
.defaultFocus($focusedField, .name)
}
}
This isn't ideal because the text field losing and gaining the focus refreshes the keyboard UI on the screen. I don't have anything better to suggest unfortunately.
Best,
——
Ziqiao Chen
Worldwide Developer Relations.