[英]how to reload tableview automatically
嗨,我正在做一個帖子屏幕,用戶可以在其中添加帖子並查看它們。這是用於查看的視圖控制器。 我正在從 firebase 獲取信息並將該信息重新加載到我的表格視圖單元格中,一切都很完美。 但是,要重新加載屏幕並查看我的帖子是否是最新的,我需要關閉應用程序並每次再次運行它,盡管我使用 .reloadData() 函數並且每次發布后它不會自動重新加載。 這是我的代碼我在哪里做錯了? 或者我錯過了什么?
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
}
好吧,我只是添加了一個復習並觀察了那里的帖子並重新加載,現在工作完美。
嘗試這個
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)
}
tableView.reloadData()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.