Nikolay Pryahin Nikolay Pryahin - 1 year ago 91
Swift Question

iOS UITextView delegate in another file

Good afternoon!

Excuse me for my English.

I've got a problem trying to assign textView's delegate to another class.

  1. I have a CommentsViewController and a ViewController in a storyBoard connected to it.

  2. I've got an UITextView element on ViewController(in storyBoard) and an outlet to CommentsViewController (called newCommentTextView).

  3. I've created a class CommentTextViewDelegate: NSObject, UITextViewDelegate.

  4. In CommentsViewController's viewDidLoad I've done this

    newCommentTextView.delegate = CommentTextViewDelegate()

  5. I've added and textViewDidChange, and textViewDidEndEditing, and _:shouldChangeTextInRange:... . But none of these functions are called, when I change textView's text!

What's wrong with me?
Thank you.

Answer Source

delegate is a weak pointer. So you need make property of CommentTextViewDelegate class, then assign it to text view delegate as per below code. After this you will be getting notify whenever any changes occur.

  let textViewDelegate = CommentTextViewDelegate()
  func viewDidLoad() {
  newCommentTextView.delegate = textViewDelegate