使用Swift保存,检索和显示动态表数据

时间:2017-09-15 16:22:49

标签: json swift uitableview interface-builder

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

我正在从json文件加载数据,格式为:

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

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

像这样:

  • UISwitch“Apple”状态:OFF
  • UISwitch“Banana”State:OFF
  • UISwitch“Orange”状态:OFF

如何定位特定开关以打开或关闭返回的项目以进行切换?

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

fruits = ["02","03"]

...并让代码找到具有该ID的行?我对如何做到这一点感到有点困惑。

加载视图时,我的最终结果如下所示:

  • UISwitch“Apple”状态:ON
  • UISwitch“Banana”State:ON
  • UISwitch“Orange”状态:OFF

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

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

假设你的水果阵列有这些水果 -

[{
    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数组。

我希望它能帮助你开始。

答案 1 :(得分:0)

如果我们考虑你的数据一秒钟,你有没有想过在你的词典中的每个项目中添加一个布尔类型的curr_int <= next_int属性。因此,当用户点击单元格或切换此单元格时,您可以将此属性值从s_i更改为enable,反之亦然。

false

而不是使用Dictionary,我会有一个引用类型数据结构,例如true,您可以在其中将字典转换为obj,反之亦然。 (不是必需的,但它会让您的生活更轻松,当然,当您保存或更新时,将该对象转换为字典)

user taps on switch 
change the enable property to true or vice versa
change switch from off to on or vice versa  
save into coreData

因此,下次用户进入您的应用程序时,交换机的状态将保存为启用状态,然后您将填充tableView,然后您应该进行检查

class
  

现在您的代码具有以下功能:保存用户的更改,并可以随时加载