当前使用 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
}
}
最佳答案
假设您有“开胃菜”、“菜肴”和“甜点”这三个部分,您可以像这样显示单元格:
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)
}
}
关于json - 在 Swift 中创建具有多个自定义单元格的 UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48262486/