swift - 在 SwiftUI 文本编辑器中设置光标位置
问题描述
有没有办法以编程方式将光标移动到特定的文本行或在 SwifUI 中选择它TextEditor
?
例如,如果有一个TextEditor
写有 10 行的 a。当用户按下按钮时,光标将导航到第 3 行,或选择文本。
解决方案
目前使用默认的 SwiftUI 是不可能的TextEditor
。NSTextField
您可以通过将(/ 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
两个方向扫描字符串,直到找到换行符。
推荐阅读
- facebook - 页面所有者的快速回复
- php - 下拉菜单选择不导航到链接
- javascript - 使用具有一个参数的函数计算数组中元素的重复次数
- php - 使用 where 子句时出现 Codeigniter 分页问题
- javascript - 根据 json 对象内的日期和时间值过滤 json 输出
- java - 如何用相机获取一个物体到另一个物体的距离?
- python - 从 h5 文件加载模型权重时轴与数组不匹配
- d3.js - 正确缩放 DOT 图形
- postgresql - 如何从 Heroku PostgreSQL 获取数据库模式?
- excel - 插入公式后的宏延迟问题 - Excel