swiftswiftuinewlinetext-editordetect

How to check / detect if user begun a new line in TextField / TextEditor?


I want to check in my TextEditor if the user pressed the "↵" (new line) button on the phones keyboard, so I can code, that on every new line the code automatically adds a "-" at the very beginning in the new line.

I want it to be like if you press return key in Microsoft Word after you entered a "-" so it's setting a "-" sign infront, like a checklist.

I found nothing that solves my problem. I played a little bit with the ".onChange" event of the TextEditor but I didn't found any solution.

Thank you for your answers in the future :)

Like mentioned above I tried ".onChanged" action and googleing.

I want it to be like in MS Word if you add a "-" in a new line it automatically adds a "-" every new line if you press the return key.


Solution

  • Here's a solution in SwiftUI:

    struct ContentView: View {
    @State private var text = ""
    
    var body: some View {
        VStack {
            Text("Enter text below:")
            TextEditor(text: $text)
                .onChange(of: text) { newValue in
                    if newValue.last == "\n" {
                        text += "-"
                    }
                }
        }
        .padding()
    }
    

    "\n" represents the "Newline" or "Line Feed" character in Swift. This character is often associated with the "Enter" or "Return" key on the keyboard. Something like this should hopefully work.