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
}
}
CodePudding user response:
I think you should be able to resolve the issue by using the code below. I would suggest we remove UITableViewCell().
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.dataSource = self
self.tableView.delegate = self
self.registerTableViewCells()
self.tableView.reloadData()
}
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "OffersTableViewCell", for: indexPath) as! OffersTableViewCell
return cell
//put any other exception conditions to display UITableViewCell() if necessary
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
CodePudding user response:
Make sure you have the Cell named - OffersTableViewCell.swift class, and OffersTableViewCell.xib that is having UI for that cell.
override func viewDidLoad() {
super.viewDidLoad()
self.registerTableViewCells()
self.tableView.dataSource = self
self.tableView.delegate = self
}
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "OffersTableViewCell", for: indexPath) as? OffersTableViewCell else { return UITableViewCell() }
cell.offerTitle.text = "blabla.."
return 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.