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.