I’m trying to populate my tableView with a custom cell – seems pretty straight forward, but for some reason when I run the following code, the custom cell doesn’t appear? I feel like I’m missing something super obvious.
Custom cell name is: OffersTableViewCell
DashboardViewController
class DashboardViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.dataSource = self
self.tableView.delegate = self
self.registerTableViewCells()
}
func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "OffersTableViewCell") as? OffersTableViewCell {
return cell
}
return UITableViewCell()
}
private func registerTableViewCells() {
let textFieldCell = UINib(nibName: "OffersTableViewCell",
bundle: nil)
self.tableView.register(textFieldCell,
forCellReuseIdentifier: "OffersTableViewCell")
}
}
OffersTableViewCell
import UIKit
class OffersTableViewCell: UITableViewCell {
@IBOutlet weak var offerTitle: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
3
Answers
I think you should be able to resolve the issue by using the code below. I would suggest we remove UITableViewCell().
Make sure you have the Cell named – OffersTableViewCell.swift class, and OffersTableViewCell.xib that is having UI for that cell.
Please register cell before you assign the tableView delegate & datasource. Or just call reloadData after you register cell Nibs.
Also, make sure you are loading safe data otherwise return default TableViewCell please.
Your code works for me. Try to go through these steps:
OffersTableViewCell
UITableViewCell
OffersTableViewCell
DashboardViewController
DashboardViewController
in app