2

Multiline TextFields can accomodate and display strings with newlines in them. e.g.

@State var text: String = “a\nb\nc\nd\ne”

var body: some View {
    TextField(“”", text: $text, axis: .vertical)
}

But there is seemingly no way to write newlines in TextFields, because TextField “submits” whenever user presses return key. i.e. it triggers call of the field’s .onSubmit() method.

A common behaviour I see, in other apps, such as Messages, and many Safari webforms, is for “return” to submit entered text, and “shift+enter” to enter a line break in text, without submitting it

I assume that the iOS Messages app is built using UITextField, not SwiftUI TextField, for the prompt field. But is there a way to get the same behaviour with SwiftUI TextField (or even TextEditor) without falling back on UIKit?

I’ve tried hacky workarounds like using .onSubmit() and .focussed() to put focus back on the TextField, and appending a newline to the text, but it doesn’t work.

  • Seems to work for me, I can add new lines at will, on MacOS 13.4, Xcode 14.3, tested on real ios 16 devices (not Previews). It could be different on older systems. You could try using `TextEditor(...)` – workingdog support Ukraine Apr 07 '23 at 09:10
  • Does this answer your question? [SwiftUI - Created a multiline textfield using axis: .vertical and onSubmit won't work now](https://stackoverflow.com/questions/73847538/swiftui-created-a-multiline-textfield-using-axis-vertical-and-onsubmit-wont) – malhal Apr 10 '23 at 10:05

0 Answers0