1

This code works and fires:

class ViewControllerDisplay: UIViewController, UITextViewDelegate {
   //.....

  let textView = MyUITextView(frame: CGRect(x:10, y:20, width:270, height:65))
  textView.params["dataname"] = _dataname
  textView.delegate = self
  view.addSubview(textView)

  func textViewDidChange(_ textView: UITextView) {
      print("YAAAA" + textView.text); 
  }

however this does not fire

  func textViewDidChange(_ textView: MyUITextView) {
      print("YAAAA" + textView.text); 
  }

here is the MyUITextView code

import UIKit
class MyUITextView: UITextView{
  var params: Dictionary<String, Any>
  required init?(coder aDecoder: NSCoder) {
      self.params = [:]
      super.init(coder: aDecoder)
  }
  init(frame: CGRect) {
      self.params = [:]
      super.init(frame: frame, textContainer: nil)
  }
}

so how do I extend the delegate to include MyUITextView in the delegate 'onChange'

Mr Heelis
  • 2,370
  • 4
  • 24
  • 34

2 Answers2

1

The method textViewDidChange (textView: MyUITextView) was not called because in the protocol UITextViewDelegate that method is specified like func textViewDidChange ( textView: UITextView)

If you need to call specifically from the custom class MyUITextView, you need to write a protocol for this class, something like:

protocol MyUITextViewDelegate {
    func myTextViewDidChange(_ textView: MyUITextView)
}

Add a field with type MyUITextViewDelegate? in class MyUITextView:

var myDelegate: MyUITextViewDelegate?

Initialize it for example in the viewDidLoad class of the ViewControllerDisplay class:

override func viewDidLoad() {
    super.viewDidLoad()
    ...
    textView.myDelegate = self
    ...
}

The class MyUITextView need to subscribe to the UITextViewDelegate protocol and implement the textViewDidChange (_ textView: UITextView) method in which our protocol is called from myDelegate if it exists:

class MyUITextView: UITextView, UITextViewDelegate {
    ...
    func someInitMethod() {
        delegate = self
    }
    ...
    func textViewDidChange(_ textView: UITextView) {
        myDelegate?.myTextViewDidChange(self) 
    }
}

And finally, by signing the class ViewControllerDisplay on the protocol MyUITextViewDelegate and implement the necessary method:

class ViewControllerDisplay: UIViewController, MyUITextViewDelegate {
    ...
    func textViewDidChange(_ textView: MyUITextView) {
        print("YAAAA" + textView.text); 
    }
}
0

ok I figured it out by casting

func textViewDidChange(_ textView: UITextView) { 
    if let sender = textView as? MyUITextView {
        let dataname = sender.params["dataname"] as? String ?? ""
        print("MyUITextView: dataname" + dataname + " = " + sender.text!)
    }
}
Mr Heelis
  • 2,370
  • 4
  • 24
  • 34