1

我依赖使用在这里创建的 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()    
        }
    }
}

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

更新

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

在此处输入图像描述

4

2 回答 2

3

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

func updateUIView(_ uiView: UITextView, context: Context) {
    let selectedRange = uiView.selectedRange
    uiView.text = text
    uiView.font = .preferredFont(forTextStyle: textStyle)
    uiView.selectedRange = selectedRange
}
于 2020-12-13T03:48:56.723 回答
0

除了Leo的回答,我注意到如果您开始使用“换行”字符进行编辑,您的 textView 也可能会跳到末尾。对我有用的是添加

func updateUIView(_ uiView: UITextView, context: Context) {
   //previous code
   uiView.scrollRangeToVisible(selectedRange)
}
于 2021-01-24T10:47:26.080 回答