Home > database >  UITextView Delegate textViewDidChange is not called
UITextView Delegate textViewDidChange is not called

Time:11-16

So I really am sorry if my post is a little off, this is my first time asking question.

I have a subclass of UITextView, let's call it A.

class A: UITextView{
   var customDelegate: CustomTextViewDelegate!
}
extension A: UITextViewDelegate{
   func textViewDidChange(_ textView: UITextView){
       if let delegate = customDelegate{
           delegate.textViewDidChange(textView)
       }
   }
   func textViewShouldChangeTextIn(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
       if let delegate = customDelegate{
           return delegate.textViewShouldChangeTextIn(baseTextView: textView, range: range, text: text)
       }
       return true
   }
}

protocol CustomTextViewDelegate{
   func textViewDidChange(_ customTextView: UITextView)
}

class SecondVC: UIViewController{}
extension SecondVC: CustomTextViewDelegate{
    func textViewShouldChangeTextIn(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool
         return false //this is where the problem is
    }

As you can see, A delegate UITextViewDelegate to itself. I instantiate A to two different ViewController. in FirstVC, textViewDidChange method from the delegate is getting called normally, but on the secondVC it does not.

Now, here is the problem, any other method from UITextViewDelegate is getting called normally on SecondVC like textView(ShouldChangeTextIn), textViewDidEndEditing. Do anyone know what is going on? and where the problem could come from?

I have tried to make sure that not a single line of code try to assign the textViewDelegate to other class.

CodePudding user response:

You have to add this line somewhere like in your viewDidLoad:

yourTextView.delegate = self

CodePudding user response:

I have found the issue, I want to simplify things when I made this post by not mentioning quite few things. But, let's just say that I make CustomTextViewDelegate so that whatever VC instantiate the A (CustomTextView) can still implement their own custom "UITextViewDelegate". The problem lies when SecondVC TextView(shouldChangeText in) from CustomTextViewDelegate return false, therefore TextViewDidChange is not getting called.

  • Related