I created a simple TableView that gets a countrylist from Firestore. The network request works fine and I don`t suspect any issue with that. All variables filled. No errors showing up in the console. But my TableView stays empty and not showing up in the UI.
Can somebody see any obvious mistakes in the code below?
import UIKit
class MainViewController: UIViewController {
[@IBOutlets...]
var countryList: [Country] = []
override func viewDidLoad() {
super.viewDidLoad()
countriesTableView.delegate = self
countriesTableView.dataSource = self
countriesTableView.register(UINib(nibName: "CountriesCell", bundle: nil), forCellReuseIdentifier: "CountriesCell")
getCountries()
}
func getCountries (){
NetworkManager.shared.getCountryList { success in
if success {
self.countryList = NetworkManager.shared.data!
self.countriesTableView.reloadData()
print (self.countryList)
}
else {
print ("Error fetching countries")
}
}
}
}
extension MainViewController: UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
populationLabel.text = countryList[indexPath.row].population
sizeLabel.text = countryList[indexPath.row].size
countryLabelMain.text = countryList[indexPath.row].name
}
}
extension MainViewController: UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print (countryList.count)
return countryList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = countriesTableView.dequeueReusableCell(withIdentifier: "CountriesCell", for: indexPath) as! CountriesCell
cell.countryLabel.text = countryList[indexPath.row].name
return cell
}
}
CodePudding user response:
You are not reloading the tableview on the main thread.
Instead of: self.countriesTableView.reloadData()
Try: DispatchQueue.main.async{[weak self] in self?.countriesTableView.reloadData() }
CodePudding user response:
Maybe the problem is with cell, set a default value for cell size, or use the default cell
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 70
}
CodePudding user response:
The following works fine for me:
override func viewDidLoad() {
super.viewDidLoad()
countriesTableView.delegate = self
countriesTableView.dataSource = self
countriesTableView.estimatedRowHeight = 60 // use as you need
countriesTableView.rowHeight = UITableView.automaticDimension
countriesTableView.register(UINib(nibName: "CountriesCell", bundle: nil), forCellReuseIdentifier: "CountriesCell")
getCountries()
}
func getCountries() {
NetworkManager.shared.getCountryList { success in
if success {
self.countryList = NetworkManager.shared.data!
DispatchQueue.main.async{ [weak self] in
self?.countriesTableView.reloadData()
}
}
else {
print ("Error fetching countries")
}
}
}