gpt4 book ai didi

json - 使用 Swift 保存、检索和显示动态表数据

转载 作者:行者123 更新时间:2023-11-28 15:19:40 25 4
gpt4 key购买 nike

我试图根据存储在 Core Data 中的结果在 Swift 中打开或关闭 UISwitch。

我正在以这种格式从 json 文件加载数据:

[{
fruit = Apple;
id = 01;
}, {
fruit = Banana;
id = 02;
}, {
fruit = Orange;
id = 03;
}

...它正在用数据填充动态表行。我有一个重复模板,行的右侧有一个 UISwitch。

像这样:

  • UISwitch“Apple”状态:OFF
  • UISwitch“香蕉”状态:OFF
  • UISwitch“橙色”状态:OFF

我如何定位一个特定的开关以打开或关闭返回的项目以打开?

我想我需要存储一组我添加到数据集中的 ID。例如

fruits = ["02","03"]

...并让代码查找具有该 ID 的行?我对如何去做这件事有点困惑。

加载 View 后,我的最终结果如下所示:

  • UISwitch“Apple”状态:ON
  • UISwitch“香蕉”状态:ON
  • UISwitch“橙色”状态:OFF

...取决于用户的选择。

如有任何帮助,我们将不胜感激。

最佳答案

假设你的水果数组有这些水果 -

[{
fruit = Apple;
id = 01;
}, {
fruit = Banana;
id = 02;
}, {
fruit = Orange;
id = 03;
}]

并选择具有这些的水果 ID 数组 -

["02","03"]

现在通过在“cellForRowAt”方法中添加这些代码片段来填充表格行 -

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell") as UITableViewCell!

let fruitsDict = fruitsArray.object(at: indexPath.row) as! NSDictionary

// I've used tag for getting fruit label and fruit switch view, you can use your own custom table view cell here for that.

let lblFruitName = cell.contentView.viewWithTag(1) as! UILabel
let fruitSwitch = cell.contentView.viewWithTag(2) as! UISwitch

lblFruitName.text = fruitsDict.value(forKey: "fruit") as? String

if(selectedFruitsIDArray.contains(fruitsDict.value(forKey: "id") as? String ?? "")){ // It contains fruit id

fruitSwitch.setOn(true, animated: true)

}
else{

fruitSwitch.setOn(false, animated: true)
}

return cell
}

fruitsArray 是您所有的水果数组,selectedFruitsIDArray 是选定的水果 ID 数组。

我希望它能帮助你开始。

关于json - 使用 Swift 保存、检索和显示动态表数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46243919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com