在 SwiftUI 文本编辑器中设置光标位置

Bat*_*gle 8 macos text-editor swift swiftui

有没有办法以编程方式将光标移动到特定的文本行或在 SwifUI 中选择它TextEditor

例如,如果有一个TextEditor10 行写在里面。当用户按下按钮时,光标将导航到,或者文本将被选中在第 3 行。

the*_*max 0

目前使用默认的 SwiftUI 是不可能的TextEditorNSTextField您可以通过将(/ UITextField) 包裹在NSViewRepresentable(/ ) 中来实现所需的行为UIViewRepresentable

我最近为 实现了这个CodeEditor。您可以在那里查看实施情况(尤其是我的 PR 中的更改)。

但是,由于您在评论之一中提到了代码,您可能也只想作为CodeEditor一个整体使用。

通过我的实现,您可以为编辑器提供到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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以通过更新来移动光标selection。如果范围为“空”,您只需将光标移动到起始索引。否则,将选择从开始(包含)到结束索引(排除)的字符。

此处提供的解决方案应该可以让您找到String.Index您想要将光标放入的行的正确位置。

如果要选择整行,请从该行开始String.Index双向扫描字符串,直到找到换行符。