ios - 在 Swift 的数组中使用多个部分和多个字典填充 TableView

标签 ios swift uitableview dictionary

我有一个 3 类别,我将其用作一个部分。在该部分中,我必须填充字典数组中的数据。这是我的代码:-

var sections = [Category A, Category B, Category C]
var itemsA = [["Item": "item A","ItemId" : "1"],["Item": "item B","ItemId" : "2"],["Item": "item C","ItemId" : "3"]]
var itemsB = [["Item": "item A","ItemId" : "1"],["Item": "item B","ItemId" : "2"],["Item": "item C","ItemId" : "3"]]
var itemsC = [["Item": "item A","ItemId" : "1"],["Item": "item B","ItemId" : "2"],["Item": "item C","ItemId" : "3"]]

func numberOfSections(in tableView: UITableView) -> Int {
    return self.sections.count
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return self.sections[section]
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return ??
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "StoreCell") as! UITableViewCell
    ????
    ????
    return cell
}

我需要明智地填充到表类别中的项目数组。如果有人能回答。谢谢!

最佳答案

使用自定义结构

struct Category {
   let name : String
   var items : [[String:Any]]
}

var sections = [Category]()

let itemsA = [["Item": "item A","ItemId" : "1"],["Item": "item B","ItemId" : "2"],["Item": "item C","ItemId" : "3"]]
let itemsB = [["Item": "item A","ItemId" : "1"],["Item": "item B","ItemId" : "2"],["Item": "item C","ItemId" : "3"]]
let itemsC = [["Item": "item A","ItemId" : "1"],["Item": "item B","ItemId" : "2"],["Item": "item C","ItemId" : "3"]]


sections = [Category(name:"A", items:itemsA), 
            Category(name:"B", items:itemsB), 
            Category(name:"C", items:itemsC)]

func numberOfSections(in tableView: UITableView) -> Int {
    return self.sections.count
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return self.sections[section].name
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let items = self.sections[section].items
    return items.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "StoreCell") as! UITableViewCell
    let items = self.sections[indexPath.section].items
    let item = items[indexPath.row]
    print(item["ItemId"] as? String)

    return cell
}

如果您对字典也使用自定义结构,您仍然可以改进代码。

关于ios - 在 Swift 的数组中使用多个部分和多个字典填充 TableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42552611/

相关文章:

ios - 多个区域的 Swift 范围信标

ios - 对 NSArray 的 JSON 响应以输出到 UITableView

ios - 在 Swift 中将 AnyObject 添加到 NSMutableArray

ios - 向下滚动点击按钮继续下一个屏幕后如何验证 CustomCell 中的 UITextField - Swift 2.3

ios - TableView 复选标记

ios - 如何在表格 View 中调整图像大小?

ios - UITextField - 只允许数字和标点符号输入/键盘

ios - Swift 4 中模板图像的渐变颜色

ios - 如何在整个视频合成中更改 CATextLayer 字符串?

iphone - 更改版本号并在 Xcode 5 中构建