首页 > 解决方案 > 在 SwiftUI 文本编辑器中设置光标位置

问题描述

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

例如,如果有一个TextEditor写有 10 行的 a。当用户按下按钮时,光标将导航到第 3 行,或选择文本。

标签: swiftmacosswiftuitext-editor

解决方案


目前使用默认的 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
        }
    }
}

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

此处提供的解决方案应允许您找到String.Index要放置光标的行的正确位置。

如果要选择整行,请从这String.Index两个方向扫描字符串,直到找到换行符。


推荐阅读