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)
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 textnewText
is the current textIf 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} ")
}
}
}
}