Search code examples
swift3delegation

Delegate not being called in Swift


I can't figure out why my Delegate is not being called. Here is where I define the protocol and call the delegate:

protocol CommentRatingViewControllerDelegate: class {
    func didCommentOrRatePost(updatedRating: Bool, addedComment:Bool)
}
class CommentRatingViewController: UIViewController, UITextViewDelegate {
    weak var delegate:CommentRatingViewControllerDelegate?
...

@IBAction func saveRatingComment(_ sender: Any) {
        var updatedRating = false
        var addedComment = false
        rating = ratingView.rating
        if rating != 0.0 {
            saveRating(articleID: post.articleID, userID: post.userID)
            updatedRating = true
        }
        if commentsTextView.text != "" {
        saveComment(articleID: post.articleID, userID: post.userID, comment: commentsTextView.text!)
        addedComment = true
    }
    self.delegate?.didCommentOrRatePost(updatedRating: updatedRating, addedComment: addedComment)
    close()
}

.... And here is where conform to the delegate protocol:

extension PostDetailViewController: CommentRatingViewControllerDelegate {
    func didCommentOrRatePost(updatedRating: Bool, addedComment: Bool) {
        if updatedRating == true || addedComment == true {
            networkingState = .searching
            if updatedRating {
                getRating(articleID: post.articleID)
            }
            if addedComment {
                post.numberOfComments += post.numberOfComments
            }
            networkingState = .finishedSearching
            tableView.reloadData()
        }
    }
}

Solution

  • When you conform to a protocol, if you want to call delegate methods, it is not enough to make your class conform to the protocol, you also need to set the delegate to self inside the class.

    class CommentRatingViewController: UIViewController, UITextViewDelegate {
        override func viewDidLoad() {
            self.delegate = self
        }
    }