【问题标题】:Fill the Tableview with Array of Dictionary and separating by section用字典数组填充表格视图并按部分分隔
【发布时间】:2020-07-10 09:29:13
【问题描述】:

如何从字典数组中填充表格视图并按部分分隔

我从 Firebase 接收数据,有时有时可能为空 2或3个项目。数据类型是字典数组[[String:Int]] 如果它有一个项目,它可以是例如:

var selectedVariation:[["ice": 20$, "cold": 30$], ["no Choco": 0$, "with Choco": 40$]]

在这种情况下,我应该将 tableview 分隔在 nonamed 2 部分中。 第一部分应包含 ["ice": 20$, "cold": 30$] 和第二部分 ["no Choco": 0$, "with Choco": 40$]

使用下面的代码,我可以只填充不带部分的 tableview,并且应该手动编写 numberOfRows

var selectedVariation: [[String:Int]]?  
var keysArray: [String] = []
var valueArray: [Int] = []


func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return selectedVariation?.count ?? 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
    return 4
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "VariationCell", for: indexPath) as! VariationTableViewCell
    for section in selectedVariation! {
    
    for (key, value) in section.sorted(by: {$0.1 < $1.1}) {        
         keysArray.append(key)
         valueArray.append(value)
    }
 
}
cell.variationName.text = keysArray[indexPath.row]
cell.variationPrice.text = "+" + String(valueArray[indexPath.row]) 
return cell
}

如果我可以在每个部分中仅勾选一项,那么奖励将是:)

【问题讨论】:

    标签: arrays swift dictionary tableview


    【解决方案1】:

    最好的解决方案是将字典映射到自定义结构,但是如果您想保留此数据模型,则表视图数据源方法是

    var selectedVariation = [["ice": 20, "cold": 30], ["no Choco": 0, "with Choco": 40]]
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return selectedVariation.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        selectedVariation[section].count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "VariationCell", for: indexPath) as! VariationTableViewCell
        let section = selectedVariation[indexPath.section]
        let key = section.keys.sorted()[indexPath.row]
        let value = section[key]!
        cell.variationName.text = key
        cell.variationPrice.text = "+" + String(value)
        return cell
    }
    

    注意:func numberOfSectionsInTableView(tableView: UITableView) -&gt; Int 是 Swift 2

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-18
      • 2020-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      相关资源
      最近更新 更多