'UITableViewCell does not show cell until I navigate to parent view controller and come back
My tableview does not show cell data until I tap on back button and return to table view controller. My app is loading data from Firebase.
class ViewPostsViewController : UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var category : String = ""
var data = [Post]()
override func viewDidLoad() {
super.viewDidLoad()
title = category.capitalized
tableView.delegate = self
tableView.dataSource = self
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
data = DataProvider.posts
tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Cell
let postsData = data[indexPath.section]
cell.viewCell(post: postsData)
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
return data.count
}
The data provider class is
static func getPost(categoryString : String) -> [Post] {
var result = [Post]()
let db = Firestore.firestore()
db.collection("posts").getDocuments() {(querySnapshot, error) in
for document in querySnapshot!.documents {
if document.get("category") as! String == categoryString {
let post = Post(title : document.get("title") as! String,
offering : document.get("offering") as! String,
category : document.get("category") as! String,
documentId : document.documentID)
result.append(post)
}
}
}
return result
}
Solution 1:[1]
You did not load tableview when calling get post method. You have to reload tableview. and don't forget add dispatch queue main thread. I hope this code will help.
static func getPost(categoryString : String) -> [Post] {
var result = [Post]()
let db = Firestore.firestore()
db.collection("posts").getDocuments() {(querySnapshot, error) in
for document in querySnapshot!.documents {
if document.get("category") as! String == categoryString {
let post = Post(title : document.get("title") as! String,
offering : document.get("offering") as! String,
category : document.get("category") as! String,
documentId : document.documentID)
result.append(post)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}
return result
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | marc_s |
