代表没有被Swift调用

时间:2017-08-13 13:00:39

标签: swift3 delegation

我无法弄清楚为什么我的代表没有被调用。 这是我定义协议并调用委托的地方:

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()
}

.... 这里符合委托协议:

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()
        }
    }
}

1 个答案:

答案 0 :(得分:2)

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
    }
}