Swift - 如何实现"like post"



我正在实施问题&使用Swift和Firebase的答案程序。我希望用户能够喜欢问题的答案。我用于处理喜欢的数据库结构是:

answerLikes
   answerID 
      userID : true
answers
   ...
posts
   ...
users
   ...

我试图根据此数据结构实施我的程序。您可以在我的tableviewController中看到代码:

@IBAction func likeButtonClicked(_ sender: UIButton) {
    if let indexPath = self.tableView.indexPathForSelectedRow {
        ref = Database.database().reference()
        print(indexPath.row)
        ref.child("answerLikes").child(answers[indexPath.row].id).observeSingleEvent(of: .value, with: {
            (snapshot) in
            let value = snapshot.value as? NSDictionary
            if value?[Auth.auth().currentUser?.uid] == nil {
                sender.setImage(UIImage(named: "filledHeart.png"), for: .normal)
                self.ref.child("answerLikes").child(self.answers[indexPath.row].id).updateChildValues([(Auth.auth().currentUser?.uid)! : true])
            } else {
                sender.setImage(UIImage(named: "emptyHeart.png"), for: .normal)
                self.ref.child("answerLikes").child(self.answers[indexPath.row].id).removeValue()
            }
        })
    }
}

我的问题是,在此功能定义中,我不知道"像按钮在哪个单元格中?"。我们通过使用IndexPath在表观视图功能中处理此问题。因此,我也尝试在此代码中使用它,但是,仅当用户单击单元格然后单击"按钮"时,我的代码才能工作。

有人可以帮我吗?我真的在这个"像帖子"功能上遇到了严重的问题。谢谢。

第一种方式

如果您使用的是自定义单元格,则可以使用协议:

protocol CustomCellDelegate: class {
    func likeButtonClicked(cell: YourCell)
}
class YourCell: UITableViewCell {
    weak var delegate: CustomCellDelegate?
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    @IBAction func likeButtonTapped(sender: AnyObject){
        delegate?.likeButtonClicked(self)
    }
}

然后将委托人添加到您的ViewController和CellForrowatIndExpath中,将其设置为您的单元格:

cell.delegate = self

最后,您可以以这种方式使用它:

func likeButtonClicked(cell: YourCell) {
    if let indexPath = self.tableView.indexPath(for: cell) {
        //....
    }
}

第二路

您可以使用按钮位置获得索引:

@IBAction func likeButtonClicked(_ sender: UIButton) {
    var buttonPosition = sender.convertPoint(.zero, to: self.tableView)
    if let indexPath = self.tableView.indexPathForRow(at: buttonPosition) {
        //.....
    }
}

第三路

在CellForrowatIndExpath中,您可以使用按钮标签:

likeButton.tag = indexPath.row

,然后:

@IBAction func likeButtonClicked(_ sender: UIButton) {
    let cellRow = sender.tag
    //...
}

最新更新