SwiftUI UITextView协调器不起作用

时间:2019-08-21 18:05:42

标签: swiftui

我将UITextView包裹在UIViewRepresentable中,并在Coordinator中加入了UITextViewDelegate,但未调用事件。我在做什么错了?


struct TextView : UIViewRepresentable {
    typealias UIViewType = UITextView

    var placeholder : String

    @Binding var text: String

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeUIView(context: UIViewRepresentableContext<TextView>) -> UITextView {
        let textView = UITextView()
        let placeholderLabel = UILabel()        
        textView.font = UIFont(name: "Helvetica", size: 16)
        placeholderLabel.restorationIdentifier = "Placeholder"
        placeholderLabel.text = self.placeholder
        placeholderLabel.font = UIFont.italicSystemFont(ofSize: (textView.font?.pointSize)!)
        placeholderLabel.sizeToFit()
        textView.addSubview(placeholderLabel)
        placeholderLabel.frame.origin = CGPoint(x: 25, y: (textView.font?.pointSize)! / 2 + 12)
        placeholderLabel.textColor = UIColor.lightGray
        placeholderLabel.isHidden = !textView.text.isEmpty

        return textView
    }

    func updateUIView(_ uiView: UITextView, context: UIViewRepresentableContext<TextView>) {
        uiView.text = self.text
    }

    class Coordinator : NSObject, UITextViewDelegate {

        var parent: TextView

        init(_ uiTextView: TextView) {
            self.parent = uiTextView
        }

        func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
            print("Not working")
            return true
        }

        func textViewDidChange(_ textView: UITextView) {
            print("Not working")
        }


    }

}


2 个答案:

答案 0 :(得分:3)

这是Xcode 11.0 beta 6中的一个有效示例:

do_homework

答案 1 :(得分:2)

您必须将textView.delegate = context.coordinator添加到makeUIView才能注册协调器,以接收来自UITextView的更新。