【问题标题】:Create UITableView with multiple Custom Cells in Swift在 Swift 中创建具有多个自定义单元格的 UITableView
【发布时间】:2018-06-24 01:18:06
【问题描述】:

使用情节提要和 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

    }
}

【问题讨论】:

  • 你想如何区分细胞??依据是什么??
  • 您想为每种类型的单元格设置一个部分,或者您想对它们应用什么类型的排序?
  • 我想为每个数组(开胃菜、菜肴、甜点)创建一个自定义单元格。
  • 是的,我想为每种类型的单元格设置一个部分。

标签: json swift uitableview


【解决方案1】:

假设您有“starters”、“dishes”和“deserts”三个部分,您可以像这样显示单元格:

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)
    }
}

【讨论】:

  • 如何以编程方式注册单元格?
猜你喜欢
  • 2015-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-27
  • 2019-12-31
相关资源
最近更新 更多