1

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.

Nikolay Pryahin
  • 377
  • 5
  • 19

2 Answers2

2

newCommentTextView.delegate = CommentTextViewDelegate() has an error.The instance of CommentTextViewDelegate has been released after viewDidLoad() is called.So CommentsViewController should own the CommentTextViewDelegate.

let textViewDelegate = CommentTextViewDelegate()
func viewDidLoad() {
   newCommentTextView.delegate = textViewDelegate
}
Tony
  • 542
  • 3
  • 13
1

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
  }