TextSelection
Represents a selection of text.
Declaration
struct TextSelectionOverview
A selection is either an insertion point (e.g. a cursor in the text), a selection over a range of text or on macOS, multiple selections.
This is frequently used to represent selection of text in a TextField or TextEditor. The following example shows a text editor that leverages text selection to offer live suggestions based on the current selection.
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...
}
}
struct SuggestionsView: View { ... }You can also use the textSelectionAffinity(_:) modifier to specify a selection affinity on the given hierarchy:
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))
}
.textSelectionAffinity(.upstream)
}
private func getSubstrings(
text: String, indices: TextSelection.Indices?
) -> [Substring] {
// Resolve substrings representing the current selection...
}
}
struct SuggestionsView: View { ... }