I have a segmented control that is filled using an enum. I have a table view to show the data of each case. What is the proper way to handle this use-case rather than hardcoding switch-cases for numberOfRowsInSection
and cellForRowAt
?
let segmentedControl = UISegmentedControl(items: SegmentedControlItems.allCases.map {$0.rawValue})
private enum SegmentedControlItems: String, CaseIterable {
case case1 = "Case1"
case case2 = "Case2"
case case3 = "Case3"
}
private var arr1 = [Type1]()
private var arr2 = [Type2]()
private var arr3 = [Type3]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch view?.segmentedControl.selectedSegmentIndex {
case 0:
return case1.count
case 1:
return case2.count
case 2:
return case3.count
default:
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: AssetView.AssetCell.reuseIdentifier, for: indexPath) as? AssetView.AssetCell else {
fatalError("Error trying to dequeue cell")
}
switch view?.segmentedControl.selectedSegmentIndex {
case 0:
setupCell(case1)
case 1:
setupCell(case2)
case 2:
setupCell(case3)
default:
return UITableViewCell()
}
return cell
}
2
Answers
Perfect article about how to use table view with different datasources. It really helped me. https://betterprogramming.pub/uitableview-sections-with-nested-types-27eabb833ad9
put
case1
,case2
, andcase3
in an array. Let’s call itcases
:Then index into that using your segmented control’s index: