使用storyboard和tableView方法创建具有多个自定义单元格的UITableView
的最佳方法是什么?
现在,我正确地将JSON
响应拆分为3个数组然后我想用它来用3个不同的自定义单元更新我的tableView。
class MainViewController: UIViewController {
// MARK: - Properties
var starters = [Starter]()
var dishes = [Dish]()
var deserts = [Desert]()
// MARK: - Outlets
@IBOutlet weak var foodTableView: UITableView!
// MARK: - Functions
func updatDisplay() {
ApiHelper.getFoods { starters, dishes, deserts in
self.starters = starters
self.dishes = dishes
self.deserts = deserts
self.foodTableView.reloadData()
}
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
updatDisplay()
}
}
extension MainViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "StarterCell", for: indexPath)
return cell
}
}
答案 0 :(得分:2)
假设您有三个部分“开始”,“菜肴”和“沙漠”,您可以显示这样的单元格:
override func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return starters.count
}
else if section == 1 {
return dishes.count
}
else {
return deserts.count
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "Starters"
}
else if section == 1 {
return "Dishes"
}
else {
return "Deserts"
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
return tableView.dequeueReusableCell(withIdentifier: "StarterCell", for: indexPath)
}
else if indexPath.section == 1 {
return tableView.dequeueReusableCell(withIdentifier: "DishesCell", for: indexPath)
}
else {
return tableView.dequeueReusableCell(withIdentifier: "DesertsCell", for: indexPath)
}
}