How to dismiss keyboard on a multi-line TextField in SwiftUI
Another situation where SwiftUI falls short.
When using the TextField initialiser containing the axis
paremeter, you no longer get access to onSubmit
but because SwiftUI is sooooo gooood at giving you warnings when you've implemented something incorrectly, it's easy to assume all is well.
Sorry, but it's not. Here's the solution and it's stupid.
@FocusState private var campaignTitleIsFocussed: Bool
TextField("New Campaign", text: $campaign.name, axis: .vertical)
.focused($campaignTitleIsFocussed)
.onChange(of: campaign.name) { newValue in
guard let newValueLastChar = newValue.last else { return }
if newValueLastChar == "\n" {
campaign.name.removeLast()
campaignTitleIsFocussed = false
}
}
How does it work?
Well, any time a new character is typed, we check to see if its a newline — user has tapped the "return" key. This appends a \n
to the end of the string. We then remove this newline, and set the focus for that TextField to false.
Easy Peasy.