Using ‘if let’ and [Any] for UITableViews with multiple cell types
Sep 4, 2018 · 1 min read
If you develop iOS apps you probably use tableviews a lot. Here is a little tip if you need to display multiple cell types in the same tableview. Sorry if this is super obvious, I don’t believe I’ve seen this before.
I used to create a class with 1 property, type. Then I’d subclass that class with my the classes that made up the content of my tableview. My array that would populate my tableView would be of the type of the parent class.
This morning I had an idea.
var items: [Any] = []class CalendarEventData {
var name: String
var date: Date }class TitleData { var title: String
}
You create your CalendarEventData and TitleData objects then put them all into ‘items’. Then use ‘if let’ in cellForRow().
extension UIViewController: UITableViewDelegate, UITableViewDataSource {public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count}public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {let titleCell = Bundle.main.loadNibNamed("TitleTableViewCell", owner: self, options: nil)?.first as! TitleTableViewCellif let titleData = listOfItems[indexPath.row] as? Title {titleCell.titleLabel.text = titleData.titlereturn titleCell}let cell = Bundle.main.loadNibNamed("CalendarEventTableViewCell", owner: self, options: nil)?.first as! CalendarEventTableViewCell if let calendarData = listOfItems[indexPath.row] as? CalendarEventData { cell.nameLabel.text = calendarData.name cell.timeLabel.text = calendarData.date }return cell}}
Works like a charm.
