'Setting the cursor position within a SwiftUI TextEditor
Is there any way to programmatically move the cursor to a specific text line or select it within a SwifUI TextEditor?
For example, if there is a TextEditor with 10 lines written in it.
When the user presses a button, the cursor will navigate to, or the text will be selected on the 3rd line.
Solution 1:[1]
This is currently not possible using the default SwiftUI TextEditor. You can achieve the desired behavior by wrapping NSTextField(/UITextField) in a NSViewRepresentable(/UIViewRepresentable).
I recently implemented this for CodeEditor. You can check out the implementation there (especially the changes from my PR).
However, since you mentioned code in one of the comments, you might also just want to use CodeEditor as a whole.
With my implementation, you can provide the editor with a binding to a Range<String.Index>.
struct ContentView: View {
static private let initialSource = "let a = 42\n"
@State private var source = Self.initialSource
@State private var selection = Self.initialSource.endIndex..<Self.initialSource.endIndex
var body: some View {
CodeEditor(source: $source,
selection: $selection,
language: .swift,
theme: .ocean,
autoscroll: true)
Button("Select All") {
selection = source.startIndex..<source.endIndex
}
}
}
You can move the cursor by updating selection. If the range is "empty" you just move the cursor to the start index. Otherwise the characters from start (included) to end index (excluded) get selected.
The solutions provided here should allow you to find the right String.Index for the line you want to place your cursor in.
If you want to select the whole line, scan the string from this String.Index in both directions until you find a newline character.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | theMomax |
