【问题标题】:How to add rows to specific section in tableview with dictionary?如何使用字典将行添加到表视图中的特定部分?
【发布时间】:2016-11-26 00:32:20
【问题描述】:

我有一本字典并从我的数据库中导入信息。我需要把它专门放在我的表格视图的正确部分。提供了所有信息,如果您需要更多详细信息或代码,我会提供。

字典输出["March 27": ["do the dishes", "take out the trash"], "March 29": ["Walk the dog", "Water the plants"], "March 28": ["Clean the house"]]

var date = ["March 27", "March 28", "March 29"]

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

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

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = table.dequeueReusableCell(withIdentifier: "cell") as! Chores
    //Having trouble on what to do here
    return cell
}

【问题讨论】:

    标签: ios swift uitableview dictionary


    【解决方案1】:

    你可以这样做,我认为这是不言自明的:

    var output = ["March 27": ["do the dishes", "take out the trash"], "March 29": ["Walk the dog", "Water the plants"], "March 28": ["Clean the house"]]
    var date = Array(output.keys)
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return date.count
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return date[section]
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return output[date[section]]?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = table.dequeueReusableCell(withIdentifier: "cell") as! Chores
        var value = output[date[indexPath.section]]?[indexPath.row] ?? ""
        cell.textLabel.text = value
        return cell
    }
    

    // 已编辑的行数:

    output[date[section]]?.count
    

    完全一样,这主要是为您提供选项,但在此示例中我将忽略它:

    let keyForSection = date[section]
    let arrayOfStringsForKey = output[keyForSection]
    let numberOfRows = arrayOfStringsForKey.count
    

    你做类似的事情来获取实际值,但不是通过计数,而是传递你想要从中获取值的行的索引

    let value = arrayOfStringsForKey[rowNumber]
    

    【讨论】:

    • 如何计算一个键下的数组数量?即"March 27" : ["...."], ["???"], "March 29": ....
    • 日期是否也通过每个键?因为对我来说它只选择第一个“March 27”
    • output[YOUR_KEY]?.count - 你问的是什么?
    • 是的,但我是否需要遍历Array(output.keys) 才能获得每个部分的计数?
    • 仍然有问题我需要在 3 月 27 日、28 日和 29 日遍历每个部分,并获取每个键中的数组数量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    相关资源
    最近更新 更多