SwiftUI TextEdit iPad external keyboard "Return" key

I can intercept the "Return" button and "Shift+Return" on an iPad's external Bluetooth keyboard with the TextField "onKeyPress" method. But - this always dismisses the keyboard. It looks like the TextField loses focus. This happens whether I return ".handled" or ".ignored".

How can I maintain focus on the TextField and not have the keyboard dismissed?

this always dismisses the keyboard. It looks like the TextField loses focus.

Since you mentioned "external Bluetooth keyboard", I am wondering what you meant about the keyboard being dismissed...

Did you mean that when you use the system-provided virtual keyboard and hit the Return key, the virtual keyboard is dismissed? If that is the case, is switching to TextEditor an option for you? I think that may be the easiest option to implement multiple line text input on iOS / iPadOS.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

Losing focus is the problem. This looks like a bug. Return and "Shift Return" should NOT lose focus - especially if it's intercepted with the "onKeyPress" method.

Is this a known bug? Will it be fixed soon? It works properly with the soft keyboard.

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.

SwiftUI TextEdit iPad external keyboard "Return" key
 
 
Q