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
}
CodePudding user response:
put case1
, case2
, and case3
in an array. Let's call it cases
:
let cases = [case1, case2, case3]
Then index into that using your segmented control's index:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let selectedItem = view?.segmentedControl.selectedSegmentIndex,
selectedItem < cases.count else { fatalError("splat!" }
return cases[selectedItem]
}
CodePudding user response:
Perfect article about how to use table view with different datasources. It really helped me. https://betterprogramming.pub/uitableview-sections-with-nested-types-27eabb833ad9