【问题标题】:send indexpath to Firebase (like button)将 indexpath 发送到 Firebase(如按钮)
【发布时间】:2017-10-19 23:30:06
【问题描述】:

我有一个表格视图,单元格中填充了来自 Firebase 的数据。在每个单元格中都有一个点赞按钮,当我喜欢特定单元格中的按钮时,它会捕获该单元格的 ID 并在 Firebase 中创建一个节点,让我知道该按钮已被点击(点赞)。在点击按钮之前,它是白色的,点击之后它变成红色。然后,如果再次单击(不喜欢)它会变成白色。

 @IBAction func LikeClicked(_ sender: UIButton) -> Void {

        let LikedRef = FIRDatabase.database().reference().child("Likes").child((self.loggedInUser?.uid)!)

        let indexPath = self.selectedIndex
        let post = self.posts![(indexPath?.row)!] as! [String: AnyObject]
        self.key = post["postID"] as? String

        let cell = TableView.cellForRow(at: indexPath!) as! ProfileTableViewCell


        if cell.Like.currentImage == #imageLiteral(resourceName: "icons8-Hearts Filled-50 (2)"){
            cell.Like.setImage(#imageLiteral(resourceName: "icons8-Heart-50"), for: .normal)
            // cell.RedLike.isHidden = true

            FIRDatabase.database().reference().child("Likes").child((self.loggedInUser?.uid)!).child(self.key!).removeValue(completionBlock: { (error, ref) in
                if error != nil {
                    print("error \(error)")
                }else{

                }})
        } else{

            LikedRef.observeSingleEvent(of: .value, with: { (snapshot:FIRDataSnapshot) in


                if let postsDictionary = snapshot .value as? [String: AnyObject] {


                    var LikeStatus = postsDictionary[self.key!] as? String ?? ""

                    if self.key == LikeStatus
                    {
                        // cell.Like.isHidden = true

                        cell.Like.setImage(#imageLiteral(resourceName: "icons8-Hearts Filled-50 (2)"), for: .normal)

                    }


                }})



            LikedRef.updateChildValues([self.key!: self.key!])


        }


    }

  cell.Like.addTarget(self, action: #selector(LikeClicked), for: UIControlEvents.touchUpInside)
    cell.Like.tag = indexPath.row
    print(indexPath.row)
    cell.Like.isUserInteractionEnabled = true

我的问题是当我喜欢特定单元格上的一个按钮时,每个单元格中的所有类似按钮都会变成红色。但我只希望我单击的单元格变为红色,当我离开应用程序并返回时,所有按钮都恢复为白色。无论用户是否退出应用程序,我都希望登录用户喜欢的任何按钮保持红色。

【问题讨论】:

  • 这个 IBAction LikeClicked 在哪里?在您的 viewController 或 tableViewCell 类中?
  • @Glenn 它位于视图控制器中

标签: ios swift uitableview firebase-realtime-database


【解决方案1】:

好的,所以我花了一个小时左右的时间来告诉你如何做你需要做的事情。喜欢和不喜欢您的自定义 UITableViewCell。我已经在每一行代码中解释了我制作的细节。我希望这能够帮到你。如果您有任何问题,请告诉我。请记住,这只是您可以完成任务的众多方法之一。

MyViewController.swift

class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, MyCustomCellDelegate {

    // This is the array of keys that we
    var likedDataKeys = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Load here the 'Likes' stuff and store its in a datasource for reference or store as well its keys.
        // If data is liked, store to likedDayaKeys the key of your data.

        FirebaseCall {
            if liked {
                self.likedDataKeys.append(keyOfYourData)
            }
        }
    }

    // MARK: - UITableViewDataSource

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = ....

        // Set the image.

        let dataKey = yourDatasource[indexPath.row] // get the key or whatever data you need

        // Set the delegate and key
        cell.delegate = self
        cell.dataKey = dataKey

        if likedDataKeys.contains(dataKey) {
            cell.image = redImageLike
        } else {
            cell.image = whiteNormalLikeImage
        }

        return cell
    }

    // MARK: - MyCustomCellDelegate

    func myCustomCell(userDidTapLikeWithDataKey dataKey: String) {
        // So now we can get the dataKey of the cell that is being liked or unliked.
        // Check from the self.likedDataKeys if the tapped cell is liked or not.

        if self.likedDataKeys.contains(dataKey) {
            // If it is there, then we should call the unlike Firebase.
            // Also remove it from the self.likedIndexPath and reload the tableView to update the image.

            let index = self.likedDataKeys.index(of: dataKey)
            self.likedDataKeys.remove(at: index)

            // Call now the unlike Firebase.

        } else {
            // If it is not there, then we should call the like Firebase.
            // Also store it to the self.likedIndexPAth
        }
    }
}

MyCustomCell.swift

protocol MyCustomCellDelegate: NSObjectProtocol {
    // This is the delegate that will help us send the dataKey reference to the viewController
    // Whenever the user taps on the like button in the cell.
    func myCustomCell(userDidTapLikeWithDataKey dataKey: String)
}

class MyCustomCell: UITableViewCell {

    // This will be called in the viewController, pass here the self of the viewController
    weak var delegate: MyCustomCellDelegate?

    // Make sure to pass here the key from the cellForRow of the viewController's tableView delegate.
    var dataKey = ""

    @IBAction func LikeClicked(_ sender: UIButton) -> Void {
        // Call the delegate to inform the viewController
        self.delegate?.myCustomCell(userDidTapLikeWithDataKey: self.dataKey)
    }
}

【讨论】:

  • 这帮助很大!非常感谢!
猜你喜欢
  • 1970-01-01
  • 2021-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-19
  • 1970-01-01
  • 2018-11-06
相关资源
最近更新 更多