GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

SOLVED: why are my tableView cells not showing?

Forums > 100 Days of Swift

Hi everyone

I create tableView that contains cells and each cell should contains an image, a label, but when I run the project in the simulator not showing cells.

https://ibb.co/SPHf5CJ

import UIKit

class ViewController: UITableViewController {

    var countries = [Country]()

    override func viewDidLoad() {
        super.viewDidLoad()

        title = "Country Facts"
        navigationController?.navigationBar.prefersLargeTitles = true

        guard let urlPath = Bundle.main.url(forResource: "data", withExtension: "json") else {fatalError()}

        if let data = try? Data(contentsOf: urlPath) {
            parse(json: data)
        } else {fatalError()}

    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        countries.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

        let country = countries[indexPath.row]
        if let cell = cell as? countryCell {
            cell.countryName.text = country.name
            cell.flagImage.image = UIImage(named: country.alphaCode)
        }
        return cell
    }

    func parse(json: Data) {

        let decoder = JSONDecoder()
        if let data = try? decoder.decode([Country].self, from: json) {
            countries = data
        }
    }
}

countryCell:

class countryCell: UITableViewCell {
    @IBOutlet var countryName: UILabel!
    @IBOutlet var flagImage: UIImageView!

how to solve this issue?

note: I tried to add heightForRowAt function, but the issue was not solved.

3      

Hi! As you didn't share your code on json structure there might be the issue with parsing. Do you have any mistakes printed to the console?

I have set it up as follows:

struct Countries: Codable {
  var results: [Country]
}

so my parsing function :

func parse(json: Data) {
    let decoder = JSONDecoder()

    if let jsonCountries = try? decoder.decode(Countries.self, from: json) {
      countries = jsonCountries.results
    }
  }

Other point to try - change your code for configuring the custom cell like so: I suspect the reason of your headache is here.

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

        let country = countries[indexPath.row]
        cell.countryName.text = country.name
        cell.flagImage.image = UIImage(named: country.alphaCode)

        return cell
    }

also pay attention that as convention class Names are capitalized in swift.

class CountryCell: UITableViewCell {
    @IBOutlet var countryName: UILabel!
    @IBOutlet var flagImage: UIImageView!
}

more information on cell customization you can find in documentation https://developer.apple.com/documentation/uikit/views_and_controls/table_views/configuring_the_cells_for_your_table

3      

Hi @ygeras , I dont got any mistakes printed in the console.

json structure code:

struct Country: Codable {
    var results: [Country]
    var name: String
    var capital: String
    var region: String
    var population: Int
    var demonym: String
    var nativeName: String
    var alphaCode: String
}

I changed cellForRowAt function, but not got solution.

3      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure and A/B test your entire paywall UI without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

share your json example.

3      

Think the model struct is wrong

struct Countries: Codable {
    var results: [Country]
}

struct Country: Codable {
    var name: String
    var capital: String
    var region: String
    var population: Int
    var demonym: String
    var nativeName: String
    var alphaCode: String
}

3      

json file:

[
   {
      "name":"Afghanistan",
      "capital":"Kabul",
      "region":"Asia",
      "population":27657145,
      "demonym":"Afghan",
      "nativeName":"افغانستان",
      "alphaCode":"AF"
   },
   {
      "name":"Åland Islands",
      "capital":"Mariehamn",
      "region":"Europe",
      "population":28875,
      "demonym":"Ålandish",
      "nativeName":"Åland",
      "alphaCode":"AX"
   }
]

I think the issue from json file!

3      

Hi @NigelGee

I following your model struct, but not solve the issue

3      

Ahh now you have shown the json file it should be

struct Country: Codable {
    var name: String
    var capital: String
    var region: String
    var population: Int
    var demonym: String
    var nativeName: String
    var alphaCode: String
}

the call should

if let jsonCountries = try? decoder.decode([Country].self, from: json) {
  countries = jsonCountries
}

3      

@NigelGee

from beggining I coding this, but I dont no what happening. I will become crazy

3      

double check if you attached identifier to your cell in storyboard. Maybe you forgot do to that? :)

(withIdentifier: "Cell", for: indexPath)

3      

There could be several reasons why your tableView cells are not showing. Here are some common issues and potential solutions to consider:

Data Source and Delegate Implementation: Ensure that you have properly implemented the UITableViewDataSource and UITableViewDelegate protocols for your table view. Make sure you have set the table view's dataSource and delegate properties to the appropriate objects.

Cell Registration or Identifier: If you are using custom table view cells, ensure that you have registered the cell class or nib with the table view using the register(:forCellReuseIdentifier:) method. Also, double-check that you are using the correct reuse identifier when dequeuing cells in the tableView(:cellForRowAt:) method.

Empty Data Source: Verify that your data source contains the necessary data to populate the table view cells. Check if the number of rows in your data source matches the number of cells you expect to see.

Table View Frame or Constraints: Check the frame or constraints of your table view to ensure it is visible and properly positioned within its superview. Make sure the table view's size and position are not obstructed by other views or elements.

Cell Configuration: Ensure that you are properly configuring the table view cells in the tableView(_:cellForRowAt:) method. Check if you are setting the cell's properties, such as text labels or images, correctly based on your data source.

Cell Height: If you have implemented a custom height for your cells using the tableView(_:heightForRowAt:) method, make sure it returns the correct height value for each row. Incorrect cell height may result in cells not being visible.

Table View Reload: If you make any changes to the data source or need to update the table view, remember to call the tableView.reloadData() method to refresh the table view and display the updated data.

By reviewing these potential issues, you should be able to identify and resolve the problem with your table view cells not showing. If the issue persists, further debugging or sharing your code can help in providing more specific assistance.

3      

I try to change cell style to Basic, but still I'm facing the same issue.

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

        let country = countries[indexPath.row]
        cell.textLabel?.text = country.name

        return cell
    }

3      

my json file was contain all countries, I created new json file contain only five countries. The issue has Finally been solved. for now my question why xcode not reading my old json file? I'm confused about that.

3      

Based on the code you provided, there are a few potential reasons why the cells may not be showing up in the simulator:

Missing cell registration: Make sure you have registered the cell class or nib with the table view before dequeuing the cells. In your viewDidLoad() method, add the following line of code: swift

Code

tableView.register(countryCell.self, forCellReuseIdentifier: "Cell")

This will ensure that the table view knows how to create cells using your custom cell class.

Incorrect cell identifier: Double-check that you have set the correct reuse identifier for the cell in your storyboard or XIB file. The reuse identifier should match the one you use in the dequeueReusableCell(withIdentifier:for:) method.

Missing or incorrect constraints: Ensure that you have set the appropriate constraints for the image view and label within the custom cell (countryCell). Make sure they have the necessary constraints to determine their size and position within the cell.

Incorrect cell subclassing: Verify that your custom cell class (countryCell) is a subclass of UITableViewCell and that you have properly set up the outlets for the label and image view.

If you have checked these potential issues and the cells still don't appear, please provide more details about the Country and countryCell classes, as well as any error messages or warnings you may encounter.

3      

I checked everything, but until now I didnt catch any mistake.

I finished the project with second json file. I hope get solution in the future for my first json file.

if somebody like to check my project https://github.com/mahoozi97/100-DAYS-OF-Swift

3      

Hi! If you change as follows:

struct Country: Codable {
    let name, capital: String
    let region: String
    let population: Int
    let demonym: String
    let nativeName: String
    let alphaCode: String? // make optional
}

and handle unwrapping accordingly where necessary. As example, I put force unwrapping here:

cell.flagImage.image = UIImage(named: country.alphaCode!)

XCode will show you where you need to handle that.

The only thing as you have only four flags in assets folder, those will pop up. The rest images will be empty. But this is understandable.

3      

I'm facing same issue, Problem solved you can also check the solutions here on these webs, also tell me if these can help you out [

url: "url here"

type: GET

];

z.setParamName("file");

Response = invokeurl

[​

3      

thank you @ygeras and thanks for all.

3      

To insert a new cell into To insert a new cell into first have to create a [tubidy mp3 download] and then add it to the table view using Cell for row at method of Table view. We can create a cell using Storyboard or by creating a nib of class UITableViewCell. first have to create a table view cell and then add it to the table view using Cell for row at method of Table view. We can create a cell using Storyboard or by creating a nib of class UITableViewCell.

3      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure and A/B test your entire paywall UI without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.