gpt4 book ai didi

ios - 当在最后一行之前+该行最后一个字符之后开始换行时,光标总是跳到 UIViewRepresentable TextView 的末尾

转载 作者:行者123 更新时间:2023-12-02 02:29:30 26 4
gpt4 key购买 nike

我依赖于使用此处创建的 UIViewRepresentable 的 TextView https://www.appcoda.com/swiftui-textview-uiviewrepresentable/ .

struct TextView: UIViewRepresentable {

@Binding var text: String
@Binding var textStyle: UIFont.TextStyle

func makeUIView(context: Context) -> UITextView {
let textView = UITextView()

textView.delegate = context.coordinator
textView.font = UIFont.preferredFont(forTextStyle: textStyle)
textView.autocapitalizationType = .sentences
textView.isSelectable = true
textView.isUserInteractionEnabled = true

return textView
}

func updateUIView(_ uiView: UITextView, context: Context) {
uiView.text = text
uiView.font = UIFont.preferredFont(forTextStyle: textStyle)
}

func makeCoordinator() -> Coordinator {
Coordinator($text)
}

class Coordinator: NSObject, UITextViewDelegate {
var text: Binding<String>

init(_ text: Binding<String>) {
self.text = text
}

func textViewDidChange(_ textView: UITextView) {
self.text.wrappedValue = textView.text
}
}
}

struct ContentView: View {

@State private var message = ""
@State private var textStyle = UIFont.TextStyle.body

var body: some View {
ZStack(alignment: .topTrailing) {
TextView(text: $message, textStyle: $textStyle)
.padding(.horizontal)

Button(action: {
self.textStyle = (self.textStyle == .body) ? .title1 : .body
}) {
Image(systemName: "textformat")
.imageScale(.large)
.frame(width: 40, height: 40)
.foregroundColor(.white)
.background(Color.purple)
.clipShape(Circle())

}
.padding()
}
}
}

我遇到的问题是每当我开始换行时 1) before 最后一行 + 2) after 该行的最后一个字符,光标总是跳在文本中的最后一个字符之后。有什么想法吗?

更新:

Leo 的回应在技术上解决了这个问题,但它似乎并不完美,因为存在不受欢迎的滚动行为,虽然插入符号位置现在是正确的,但不会停止自动滚动到底部。见下文:

enter image description here

最佳答案

在 updateUIView 方法中设置文本属性后,您可以保存插入符号位置 (selectedRange) 并设置 TextView 的选定范围:

func updateUIView(_ uiView: UITextView, context: Context) {
let selectedRange = uiView.selectedRange
uiView.text = text
uiView.font = .preferredFont(forTextStyle: textStyle)
uiView.selectedRange = selectedRange
}

关于ios - 当在最后一行之前+该行最后一个字符之后开始换行时,光标总是跳到 UIViewRepresentable TextView 的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65270192/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com