I tried with onChange, but could not extract the string:
var body: some View {
TextField("Placehodler",
text: $myText,
selection: $textSelection)
.onChange(of: textSelection) {
print("change of selection: \(textSelection)")
}
}
I get
change of selection: Optional(SwiftUI.TextSelection(indices: SwiftUI.TextSelection.Indices.selection(Range(Swift.String.Index(_rawBits: 131080)..<Swift.String.Index(_rawBits: 393224))), affinity: SwiftUI.TextSelectionAffinity.upstream))
But that leads nowhere.
However, TextSelection doc hints at a way to extract strings, but does not show how to retrieve substrings:
struct SuggestionTextEditor: View {
@State var text: String = ""
@State var selection: TextSelection? = nil
var body: some View {
VStack {
TextEditor(text: $text, selection: $selection)
// A helper view that offers live suggestions based on selection.
SuggestionsView(
substrings: getSubstrings(text: text, indices: selection?.indices))
}
}
private func getSubstrings(
text: String, indices: TextSelection.Indices?
) -> [Substring] {
// Resolve substrings representing the current selection...
}
}
That let me hope there is a solution…