json - 在 Swift 中创建具有多个自定义单元格的 UITableView

标签 json swift uitableview

当前使用 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/

相关文章:

iphone - 如何在具有从数据库获取内容的 UITableView 中实现按字母顺序排列的节标题

java - 如何检索 JSONObject 子字段?

ios - CollectionView 在我的聊天 View 中按顺序更新和复制。 ( swift 4.2,Xcode)(MessengerKit)

macos - Swift - 从 NSViewController 捕获按键

ios - UITableViews 之间的间距,如设置应用程序

ios - 如何从 nsdictionary 中获取选定值的键

json - 如何使用 GROUP BY 子句将正确的属性名称设置为 json 聚合结果?

java - JSON 响应表示更新的变量为空

python - 使自定义类 JSON 可序列化

ios - Swift 中的 Int 到 UInt(反之亦然)位转换