SwiftUI UITextView Coordinator not working

前端 未结 2 671
盖世英雄少女心
盖世英雄少女心 2021-01-12 18:38

I have wrapped a UITextView in a UIViewRepresentable and included a Coordinator as UITextViewDelegate, but the events are

相关标签:
2条回答
  • 2021-01-12 19:14

    You have to add textView.delegate = context.coordinator to makeUIView to register the coordinator to receive updates from UITextView.

    0 讨论(0)
  • 2021-01-12 19:18

    This is a working example in Xcode Version 11.0 beta 6:

    import SwiftUI
    
    struct ContentView: View {
         @State var text = ""
    
           var body: some View {
            VStack {
                Text("text is: \(text)")
                TextView(
                    text: $text
                )
                    .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
            }
    
           }
    }
    
    struct TextView: UIViewRepresentable {
        @Binding var text: String
    
        func makeCoordinator() -> Coordinator {
            Coordinator(self)
        }
    
        func makeUIView(context: Context) -> UITextView {
    
            let myTextView = UITextView()
            myTextView.delegate = context.coordinator
    
            myTextView.font = UIFont(name: "HelveticaNeue", size: 15)
            myTextView.isScrollEnabled = true
            myTextView.isEditable = true
            myTextView.isUserInteractionEnabled = true
            myTextView.backgroundColor = UIColor(white: 0.0, alpha: 0.05)
    
            return myTextView
        }
    
        func updateUIView(_ uiView: UITextView, context: Context) {
            uiView.text = 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 {
                return true
            }
    
            func textViewDidChange(_ textView: UITextView) {
                print("text now: \(String(describing: textView.text!))")
                self.parent.text = textView.text
            }
        }
    }
    
    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ContentView()
        }
    }
    
    0 讨论(0)
提交回复
热议问题