5

How to do this in SwiftUI in TextEditor? I thought of reading return from keyboard. TextField has onEditingChanged and onCommit, but TextEditor doesn't.

In Notes app it detects automatically the numbered list, and has button for adding bulleted list.

I specifically want it to add number/bullet after empty line. (if possible)

enter image description here

MikeMaus
  • 385
  • 3
  • 22

1 Answers1

9

You can observe changes to the TextEditor's text with onChange. Then, by doing [text] newText, you can capture both the old and new value.

  • text is the previous text
  • newText is the current text

If you compare these, you can ensure that bullet points are only added when the user is typing, and not when they're deleting.

Note that my implementation doesn't handle pasting large ranges of text yet.

struct ContentView: View {
    @State var text = "\u{2022} "

    var body: some View {
        TextEditor(text: $text)
            .frame(height: 400)
            .border(Color.black)
            .onChange(of: text) { [text] newText in
                if newText.suffix(1) == "\n" && newText > text {
                    self.text.append("\u{2022} ")
                }
            }
    }
}

When entering new lines, a bullet point is inserted at the start of the line

aheze
  • 24,434
  • 8
  • 68
  • 125
  • thanks! maybe you have an idea, how to make proper indentation if point is multiline, i've tried just to add couple of `" "` white spaces...(but didn't like it) – MikeMaus May 16 '21 at 16:44
  • 1
    @MikeMaus I think in that case, it would be best to add the bullet points in a separate view (not inside the text editor). It would definitely be more complicated though, maybe post it into another question? – aheze May 16 '21 at 16:56