【问题标题】:refresh tableView after deleting cell删除单元格后刷新tableView
【发布时间】:2017-07-01 08:12:19
【问题描述】:

我有一个从 Firebase 填充数据的 tableView,当我单击删除按钮时,数据会从 Firebase 中删除,但它仍保留在我的应用程序中,并且在我关闭应用程序并重新打开它之前它不会从 tableView 中删除数据.以下是我设置删除功能的方法:

func deletePost() {
        let uid = FIRAuth.auth()!.currentUser!.uid
        let storage = FIRStorage.storage().reference(forURL: "gs://gsignme-14416.appspot.com")
        FIRDatabase.database().reference().child("posts").child(uid).observe(.childAdded, with: { (snapshot) in

            let indexPath = self.selectedIndex

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

            self.itemsRef = FIRDatabase.database().reference().child("posts").child(uid).child(self.key!)


        // Remove the post from the DB
        FIRDatabase.database().reference().child("books").child(self.key!).removeValue { error in
            if error != nil {
                print("error \(error)")
            }
        }

            })
        self.TableView.reloadData()
    }

这里是委托和数据源:

    func numberOfSections(in tableView: UITableView) -> Int {
            // #warning Incomplete implementation, return the number of sections
            return 1
        }

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
         posts.count
}

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       self.selectedIndex = indexPath
        self.didExpandCell()
        if isExpanded && self.selectedIndex == indexPath{
            print(indexPath)
        } else{
                    }}

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        if isExpanded && self.selectedIndex == indexPath{
            return 300
        }
              return 126
    }


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cells", for: indexPath) as! ProfileTableViewCell

        //Configure the cell
        let post = self.posts[indexPath.row] as! [String: AnyObject]
        cell.Title.text = post["title"] as? String
        cell.Author.text = post["Author"] as? String
        cell.ISBN10.text = post["ISBN10"] as? String
        return cell
    }

我试图在函数末尾添加一个 tableview.reloaddata 但这没有帮助。我做错了什么?

【问题讨论】:

  • 请发布您的 tableview 委托和数据源函数,因为这些信息不足以提供帮助!
  • 需要在removeValue的回调中调用reloadData()。
  • @SteffenSchmitz 这也不起作用
  • 那你能把控制器的其余部分贴出来吗?尤其是在哪里分配 tableView 委托和委托实现?
  • posts 数组中删除您的对象,然后在主队列中重新加载您的表视图,然后从 Firebase 中删除您的对象。

标签: ios swift uitableview firebase-realtime-database


【解决方案1】:

posts 数组中删除您的对象,然后在主队列中重新加载您的tableView,您可以从firebase 中删除您的对象。

检查以下代码:

func deletePost() {
    let uid = FIRAuth.auth()!.currentUser!.uid
    let storage = FIRStorage.storage().reference(forURL: "gs://gsignme-14416.appspot.com")
    FIRDatabase.database().reference().child("posts").child(uid).observe(.childAdded, with: { (snapshot) in

        let indexPath = self.selectedIndex

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

        self.itemsRef = FIRDatabase.database().reference().child("posts").child(uid).child(self.key!)


        // Remove the post from the DB
        FIRDatabase.database().reference().child("books").child(self.key!).removeValue { error in
            if error != nil {
                print("error \(error)")
            } else {
                //Here remove your object from table array
                self.posts.remove(at: indexPath?.row)
                //Reload your tableview in main queue
                DispatchQueue.main.async{
                    self.TableView.reloadData()
                }
            }
        }

    })
}

没有测试过,如果您对上述代码仍有问题,请告诉我。

【讨论】:

  • 我不确定我做错了什么,但删除后单元格仍然存在
  • 你能分享任何演示项目吗?或在删除对象后检查打印。
  • @juelizabeth 之后尝试在 Firebase 控制台中添加一个孩子。您在 deletePost 函数中将 EventListener 注册到“.childAdded”。 removeValue 方法只有在你调用 deletePost 并添加了一个子节点后才会被调用。
  • @SteffenSchmitz 我不太确定该怎么做
  • @juelizabeth 尝试删除 ` FIRDatabase.database().reference().child("posts").child(uid).observe(.childAdded, with: { (snapshot) in `删除块周围的部分。由于您不在代码中使用快照,因此您不需要它。我不确定何时调用 .childAdded,但这可能是一个问题。
【解决方案2】:
        func deletePost() {
                let uid = FIRAuth.auth()!.currentUser!.uid
                let storage = FIRStorage.storage().reference(forURL: "gs://gsignme-14416.appspot.com")
                FIRDatabase.database().reference().child("posts").child(uid).observe(.childAdded, with: { (snapshot) in

                    let indexPath = self.selectedIndex

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

                    self.itemsRef = FIRDatabase.database().reference().child("posts").child(uid).child(self.key!)


                // Remove the post from the DB
                FIRDatabase.database().reference().child("books").child(self.key!).removeValue { error in
                    if error != nil {
                        print("error \(error)")
                        return // use return here or use if else
                    }
// no error has occurred,hence move on to remove the post from the array
              self.posts.remove(at: indexPath.row)
 }     })
                DispatchQueue.main.async {
                   self.TableView.reloadData()
                 }

            }

【讨论】:

  • 您还应该在回调中重新加载数据。
【解决方案3】:

同时从您的数组中删除已删除的对象。您的表格视图使用 posts 数组填充,而不是来自 Firebase 对象本身。当您单击删除按钮时,数据将从 Firebase 中删除,但仍保留在您的应用程序中,因为您尚未从数组中删除该对象,即 posts 这就是为什么它不会从 tableView 中删除数据,直到您关闭应用程序和重新打开它。

您需要从您的帖子数组中删除已删除的对象并重新加载该行以获得效果。

 self.posts.remove(at: indexPath.row)

然后重新加载该特定行本身。

 self.tableView.beginUpdates
 tableView.reloadRows(at: [indexPath], with: .top)
 self.tableView.endUpdates;

你的情况

 FIRDatabase.database().reference().child("books").child(self.key!).
   removeValue { error in
        if error != nil {
            print("error \(error)")
        } else{
          self.posts.remove(at: indexPath.row)
          self.tableView.beginUpdates
          tableView.reloadRows(at: [indexPath], with: .top)
          self.tableView.endUpdates;
        }
    }
  })

希望对您有所帮助。快乐编码!

【讨论】:

  • 当我将 self.tableView.beginUpdates 放入 deletePost 函数时,我得到表达式解析为未使用的函数
  • 这是我为了运行它而做的self.posts.remove(at: indexPath?.row) self.TableView.beginUpdates() self.TableView.reloadRows(at: [indexPath!], with: .top); self.TableView.endUpdates();
猜你喜欢
  • 2016-11-21
  • 1970-01-01
  • 1970-01-01
  • 2013-06-11
  • 1970-01-01
  • 1970-01-01
  • 2015-10-03
  • 2014-04-29
  • 2018-05-25
相关资源
最近更新 更多