不幸的是,似乎没有“纯粹的” SwiftUI 解决方案。实现您所描述的唯一选择似乎是在 UIKit 中实现整个视图并将其集成到您的应用程序的其余部分中UIViewRepresentable
。
不过,既然您询问了 SwiftUI,我可以向您展示仅使用它可以走多远。
获取光标位置
您在这里有两个选择。首先,您可以使用Introspect包。它允许您访问用于实现某些 SwiftUIView
的底层 UIKit 元素。这看起来像这样:
import SwiftUI
import Introspect
struct ContentView: View {
@State var items: [String] = ["Apples", "Oranges", "Bananas", "Pears", "Mangos", "Grapefruit","Apples", "Oranges", "Bananas", "Pears", "Mangos", "Grapefruit"]
@State private var newItemText : String = ""
@State private var uiTextView: UITextView?
@State private var cursorPosition: Int = 0
var body: some View {
ScrollViewReader { (proxy: ScrollViewProxy) in
List{
ForEach(items, id: \.self) {
Text("\($0)")
}
TextEditor(text: $newItemText)
.introspectTextView { uiTextView in
self.uiTextView = uiTextView
}
.onChange(of: newItemText) { newValue in
if let textView = uiTextView {
if let range = textView.selectedTextRange {
let cursorPosition = textView.offset(from: textView.beginningOfDocument, to: range.start)
self.cursorPosition = cursorPosition
}
}
}.id("New Item TextField")
}
}
}
}
但是请注意,这种方法可能会在 SwiftUI 的未来版本中失效,因为 Introspect 包依赖于内部 API,并且可能不再能够UITextView
从TextEditor
.
另一种解决方案可能是在每次更改时仅将newValue
ofnewItemText
与旧的进行比较,然后 - 从末尾开始 - 比较每个索引的字符,直到发现不匹配。请注意,如果用户决定输入一长串相同的字符,这是有问题的。a
例如,在比较"aaaaaaa"
和时,您不知道插入的位置"aaaaaa"
。
滚动
我们现在知道光标在文本中的位置。但是,由于我们不知道空格和换行符在哪里,所以我们不知道光标在什么高度。
我发现解决这个问题的唯一方法——我知道这听起来有多混乱——是渲染一个版本,TextEditor
其中包含的文本在光标位置被截断,并使用 a 测量其高度GeometryReader
:
struct ContentView: View {
@State var items: [String] = ["Apples", "Oranges", "Bananas", "Pears", "Mangos", "Grapefruit","Apples", "Oranges", "Bananas", "Pears", "Mangos", "Grapefruit"]
@State private var newItemText : String = ""
@Namespace var cursorPositionId
@State private var cursorPosition: Int = 0
@State private var uiTextView: UITextView?
@State private var renderedTextSize: CGSize?
@State private var renderedCutTextSize: CGSize?
var anchorVertical: CGFloat {
if let renderedCutTextSize = renderedCutTextSize, let renderedTextSize = renderedTextSize, renderedTextSize.height > 0 {
return renderedCutTextSize.height / renderedTextSize.height
}
return 1
}
var body: some View {
ZStack {
List {
VStack {
Text(newItemText)
.background(GeometryReader {
Color.clear.preference(key: TextSizePreferenceKey.self,
value: $0.size)
})
Text(String(newItemText[..<(newItemText.index(newItemText.startIndex, offsetBy: cursorPosition, limitedBy: newItemText.endIndex) ?? newItemText.endIndex)]))
.background(GeometryReader {
Color.clear.preference(key: CutTextSizePreferenceKey.self,
value: $0.size)
})
}
}
ScrollViewReader { (proxy: ScrollViewProxy) in
// ...
}
}
.onChange(of: newItemText) { newValue in
// ...
}
.onPreferenceChange(CutTextSizePreferenceKey.self) { size in
self.renderedCutTextSize = size
}
.onPreferenceChange(TextSizePreferenceKey.self) { size in
self.renderedTextSize = size
}
}
}
private struct TextSizePreferenceKey: PreferenceKey {
static let defaultValue = CGSize.zero
static func reduce(value: inout CGSize, nextValue: () -> CGSize) {
let newVal = nextValue()
value = CGSize(width: value.width + newVal.width, height: value.height + newVal.height)
}
}
private struct CutTextSizePreferenceKey: PreferenceKey {
static let defaultValue = CGSize.zero
static func reduce(value: inout CGSize, nextValue: () -> CGSize) {
let newVal = nextValue()
value = CGSize(width: value.width + newVal.width, height: value.height + newVal.height)
}
}
该属性提供了相对于总高度anchorVertical
的光标所在高度的良好估计。TextEditor
从理论上讲,我们现在应该能够使用以下方法滚动到TextEditor
's 高度的这个百分比ScrollViewProxy
:
ScrollViewReader { (proxy: ScrollViewProxy) in
List{
ForEach(items, id: \.self) {
Text("\($0)")
}
TextEditor(text: $newItemText)
.introspectTextView { uiTextView in
self.uiTextView = uiTextView
}
.id(cursorPositionId)
}
.onChange(of: cursorPosition) { pos in
proxy.scrollTo(cursorPositionId, anchor: UnitPoint.init(x: 0, y: anchorVertical))
}
}
不幸的是,这不起作用。UnitPoint
具有自定义坐标的初始化程序,但是,scrollTo(_:anchor:)
对于非整数值的行为不符合预期。即UnitPoint.top.height = 0.0
工作UnitPoint.bottom.height = 1.0
正常,但无论我在两者之间尝试什么数字(例如0.3
或0.9
),它总是滚动到文本中相同的随机位置。
这要么是 SwiftUI 中的错误,要么scrollTo(_:anchor:)
从未打算与 custom/decimal 一起使用UnitPoint
。
因此,我看不到使用 SwiftUI API 让它滚动到正确位置的方法。
一个合理的解决方案
我看到你有两个选择:要么在 UIKit 中实现整个子视图,要么稍微减少你的要求:
如果 cursorPosition 位于/接近字符串的末尾,您可以将 与cursorPosition
的newValue
长度进行比较,并且仅滚动到底部。.onChange(of: newItemText)