hi everyone, any thought on how to implement a RichText(markdown) live editor using the new TextEditor(text: AttributedString, selection: AttributedTextSelection)
?
Having issues like:
- how to get the location of the selected text relatived to the TextEditor bounds, which is used to show and position a floating toolbar.
- how to detect the cursor point is a new line and the content is "# ", (of couse now the user enter a space after the "#"), and if so, how to apply a H1 heading format to that line
much more issues like this, but these two are how to get me started, thanks
struct TextEditor8: View {
@State var text: AttributedString
@State var selection = AttributedTextSelection()
@State var isShowFloatingToolbar = false
@State var toolbarPosition: CGPoint = .zero
init() {
var text = AttributedString("Hello ✋🏻,Who is ready for Cooking?")
let range = text.characters.indices(where: \.isUppercase)
text[range].foregroundColor = .blue
_text = State(initialValue: text)
}
var body: some View {
ZStack(alignment: .topLeading) {
GeometryReader { geo in
TextEditor(text: $text, selection: $selection)
.onChange(of: selection, perform: { newV in
let v = text[newV]
if v.characters.isEmpty {
isShowFloatingToolbar = false
} else {
isShowFloatingToolbar = true
toolbarPosition = CGPoint(x: 20, y: 20) // how to get CGPoint relatived to TextEditor from selection
}
print("vvvv", v.characters.isEmpty)
})
}
if isShowFloatingToolbar {
FloatingToolbarAtSelection()
.position(toolbarPosition)
}
}
}
}