Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Created a multiline textfield using axis: .vertical and onSubmit won't work now

Tags:

swift

swiftui

Basically I created a multiline textField, but pressing onSubmit won't work at all. I rather it submit when double pressing return or something similar.

If there is a way to avoid collapsing the keyboard when submitting instead of using multiline I would be grateful to be told how.


1 Answers

This is the workaround that I've used:

struct SwiftUIView: View {
    
    @State var text: String = ""
    
    var body: some View {
        TextField("text", text: $text, axis: .vertical)
            .frame(width: 200, height: 200)
            .multilineTextAlignment(.leading)
            .textFieldStyle(.roundedBorder)
            .font(.title)
            .onChange(of: text) { newValue in
                guard let newValueLastChar = newValue.last else { return }
                if newValueLastChar == "\n" {
                    text.removeLast()
                    hideKeyboard()
                }
            }
    }
}

Being hideKeyboard a function defined in an extension of View:

extension View {
    func hideKeyboard() {
        UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
    }
}
like image 53
tecosabri Avatar answered Dec 21 '25 20:12

tecosabri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!