I have followed this stackoverflow question & answer as guide to create a custom cell inside table view (without adding a prototype cell in the storyboard), However I was not able to create a table view with the custom cells, I just get rows of empty cells. I did look at other SO questions but they did not help.
I believe I am doing something wrong with the way I register the cell.
(FYI: When I add a prototype cell to my table view and assign it a class and cell id and if I then disable tableView.register(AppointmentTVCell.self, forCellReuseIdentifier: cellId)
it works, I am not interested in this since I want to minimise the use of IB)
Below is my tableViewController in storyboard, to which a table view class AppointmentsTVC
has been assigned
Below is my code for the Table View Controller
class AppointmentsTVC: UITableViewController {
let cellId = "reuseIdentifier"
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(AppointmentTVCell.self, forCellReuseIdentifier: cellId)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 2
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print("Cell for Row at func called")
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! AppointmentTVCell // Creating a cell
cell.caseId.text = "123456"
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 150.0
}
}
Below is my code for the custom table view cell
class AppointmentTVCell: UITableViewCell {
let caseId: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 14)
label.frame = CGRect(x: 0, y: 50, width: 100, height: 30)
label.numberOfLines = 2
//label.text = "Hello"
label.textColor = UIColor.black
return label
}()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
contentView.addSubview(caseId)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}