如何自动重新加载tableview [英] how to reload tableview automatically

查看:30
本文介绍了如何自动重新加载tableview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个帖子屏幕,用户可以在其中添加帖子并查看它们.这是用于查看的视图控制器.我正在从 firebase 获取信息并将该信息重新加载到我的表格视图单元格中,一切都很完美.但是,要重新加载屏幕并查看我的帖子是否是最新的,我需要关闭应用程序并每次再次运行它,尽管我使用 .reloadData() 函数并且每次发布后它不会自动重新加载.这是我的代码我在哪里做错了?还是我遗漏了什么?

Hi I am doing a post screen where users add post and view them.This is the viewcontroller for viewing. I am getting information from firebase and reload that info to my table view cells everything is going perfect. However to reload the screen and see if my posts are up to date I need to close the application and run it again each time although I use .reloadData() function and it doesn't reload automatically after each posting. here is my code where do I do the mistake? or am I missing something?

override func viewDidLoad() {
    super.viewDidLoad()
    self.navcik.title = "Posts"
    tableView = UITableView(frame:view.bounds, style: .plain)
    view.addSubview(tableView)
    let cellnib = UINib(nibName: "postTableCell", bundle: nil)
    tableView.register(cellnib, forCellReuseIdentifier: "postCell")

    tableView.delegate = self
    tableView.dataSource = self
    tableView.reloadData()
    observeposts()
}
func observeposts() {
    let db = Firestore.firestore()
    db.collection("posts").getDocuments { (snap, error) in
        var tempposts = [Post]()
        if error != nil {
            print("error:\(String(describing: error))")
        } else {
            for document in snap!.documents {
                if let dict = document.data() as? [String: Any] ,
                let username = dict["username"] as? String,
                let title = dict["title"] as? String,
                    let desc = dict["desc"] as? String {
                    let post = Post(id: "1", username: username, title: title, desc: desc)
                    tempposts.append(post)
                }

            }
            self.posts = tempposts
            self.tableView.reloadData()
        }

    }
}
@IBOutlet weak var navcik: UINavigationItem!

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! postTableCell
    cell.set(post: posts[indexPath.row])
    return cell
}

推荐答案

好吧,我刚刚添加了一个复习,并观察了那里的帖子并重新加载,现在工作完美.

Well I just added a refresher and observed the posts there and reloaded, works perfect now.

这篇关于如何自动重新加载tableview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆