Swift - 如何实现“点赞帖子”

Posted

技术标签:

【中文标题】Swift - 如何实现“点赞帖子”【英文标题】:Swift - How to implement "like post" 【发布时间】:2017-12-17 16:11:56 【问题描述】:

我正在使用 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 来处理这个问题。所以我也尝试在这段代码中使用它,但是,我的代码只有在用户单击单元格然后单击like按钮时才有效。

谁能帮我解决这个问题?我真的对这个“赞帖子”功能有严重的问题。谢谢。

【问题讨论】:

【参考方案1】:

第一种方式

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

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
    //...

【讨论】:

你成就了我的一天,我非常感谢你。很好的指导! 又是我,很抱歉打扰您,您能帮我数一下点赞数吗?我遇到了麻烦。我可以用“snapshot.childrenCount()”计算点赞的数量,但我希望页面在用户点击点赞按钮时更新点赞数。我想我应该在 likeButtonClicked 函数中处理它,但找不到方法。

以上是关于Swift - 如何实现“点赞帖子”的主要内容,如果未能解决你的问题,请参考以下文章

如何通过 Swift 扩展实现委托方法

Swift - 如何实现登录/会话(无代码)

Swift如何实现通用类型的弱引用数组(上)

如何在符合 Swift 协议的同时确定要实现哪些成员

Swift如何实现通用类型的弱引用数组(下)

Swift:如何实现用户定义的运行时属性