uitableviewuikitcustom-cell

Custom cell is registered and used in TableView controller but in app is default cell


I want to use my custom cell in UITableViewController which is used in TableViewController. I register custom cell and used it in cellForRowAt method. Cell is "created" in storyboard. All classes for controllers are setted and identifiers as well, for custom cell is also selected class and identifier. But when I launch my app it shows default empty cells. Here is my code:

class TabBarController: UITabBarController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let beersList = BeersListModuleBuilder.createBeersListView()
        let beersListNavController = UINavigationController(rootViewController: beersList)
        beersListNavController.tabBarItem = UITabBarItem(title: "All beers", image: nil, tag: 1)
        
        let favoriteBeersList = UIViewController()
        let favoriteBeersListNavController = UINavigationController(rootViewController: favoriteBeersList)
        favoriteBeersListNavController.tabBarItem = UITabBarItem(title: "Favorites", image: nil, tag: 2)
        self.viewControllers = [beersListNavController, favoriteBeersListNavController]
    }
}

class BeersListTableViewController: UITableViewController{

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.register(BeerCell.self, forCellReuseIdentifier: "BeerCell")
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 20
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "BeerCell", for: indexPath) as! BeerCell
        cell.beerName?.text = "beer.name"
        cell.beerABV?.text = "beer.abv"
        cell.addToFavoritesButton?.setImage(UIImage(systemName:"star"), for: .normal)
        return cell
    }
}

class BeerCell: UITableViewCell {
    @IBOutlet var beerName: UILabel!
    @IBOutlet var beerABV: UILabel!
    @IBOutlet var addToFavoritesButton: UIButton!
}

enter image description here

enter image description here

enter image description here

enter image description here

GitHub repo: https://github.com/IgorShevtshenko/BeerList


Solution

  • Just remove this line:

    self.tableView.register(BeerCell.self, forCellReuseIdentifier: "BeerCell")
    

    When you use prototype cells in a storyboard scene, the storyboard registers the class against the reuse identifier for you. You need to register your cell only if you are using custom class or nib.