【问题标题】:Need suggestion removing data from dictionary需要建议从字典中删除数据
【发布时间】:2021-04-26 19:14:31
【问题描述】:

我有一本结构如下的字典:

[0:["var1":"var1Value","var2":"var2Value", 1:["var1":"var1Value","var2":"var2Value", 2:["var1":"var1Value","var2":"var2Value"]

我正在使用它来显示在 TableView 中:

cell.title.text = dict[indexPath.row]?["var1"]

上面的代码工作正常,但是当我使用 .delete 编辑样式在 TableView 中滑动删除,并删除中间值时,它会弄乱我的 TableView,因为 dict 现在有 0: 和 2: 因为我们删除了1: 所以现在 cellForRowAt 正在寻找 0: 和 1: 当 dict 实际上是 0: 2:

滑动删除代码:

dict.remove(at: indexPath.row)

结果字典:

[0:["var1":"var1Value","var2":"var2Value", 2:["var1":"var1Value","var2":"var2Value"]

这反过来不会让 tableView 单元格正确显示。

下面的代码似乎正在运行。这会起作用还是可能会在将来引起问题?

func deleteFromArray(at:Int){
        var count = at
        while dict[count] != nil {
            dict[count] = dict[count+1]
            count += 1
        }
        
        ItemsTableView.reloadData()
    }

感谢大家的帮助

【问题讨论】:

  • 不要使用Dictionary,而是使用Array。
  • @Larme 我愿意,但它们需要以某种方式被吸入单独的阵列中。就像我有 0: 1: 和 2:
  • 你可以有一个字典数组。或者更好的自定义结构数组。

标签: swift xcode dictionary tableview


【解决方案1】:

字典不适用于表格视图或集合视图的模型。按照 Larme 的建议使用数组。

您说需要单独的数组,但目前您的模型中没有任何数组。现在你有一本字典。

您可以创建一个结构来表示表格视图中的一个单元格,并让模型成为这些结构的数组。

编辑:

可能看起来像这样:

struct CellModel {
    let title: String
    let iconName: String
    let description: String
}

var tableViewModel: [CellModel] = [
    CellModel(title: "A Thing",
              iconName: "AnImageOfThing",
              description: "This is a thing to go in the table view"),
    CellModel(title: "Another Thing",
              iconName: "AnImageOfAnotherThing",
              description: "This is another thing to go in the table view"),
    CellModel(title: "Yet Another Thing",
              iconName: "AnImageOfYetAnotherThing",
              description: "This is yet another thing to go in the table view")
]


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell: MyCell = tableview.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as? MyCell else {
        fatalError("Unable to dequeue cell")
    }
    let cellData = tableViewModel[indexPath.row] 
    cell.title = cellData.title
    cell.imageView.image = UIImage(named: cellData.iconName)
    cell.descriptionField.text = cellData.description
    return cell
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-30
    • 1970-01-01
    • 2014-12-06
    • 1970-01-01
    • 2022-10-20
    • 1970-01-01
    相关资源
    最近更新 更多