Swift 中未调用委托
Delegate not being called in Swift
我不明白为什么我的委托没有被调用。
这是我定义协议并调用委托的地方:
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()
}
}
}
当你遵守一个协议的时候,如果你想调用委托的方法,仅仅让你的class遵守协议是不够的,你还需要将委托设置为self
在 class.
里面
class CommentRatingViewController: UIViewController, UITextViewDelegate {
override func viewDidLoad() {
self.delegate = self
}
}
我不明白为什么我的委托没有被调用。 这是我定义协议并调用委托的地方:
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()
}
}
}
当你遵守一个协议的时候,如果你想调用委托的方法,仅仅让你的class遵守协议是不够的,你还需要将委托设置为self
在 class.
class CommentRatingViewController: UIViewController, UITextViewDelegate {
override func viewDidLoad() {
self.delegate = self
}
}