[英]Saving, retrieving and displaying dynamic table data with Swift
我试图从存储在核心数据中的结果中打开或关闭Swift中的UISwitch。
我正在从json文件中以以下格式加载数据:
[{
fruit = Apple;
id = 01;
}, {
fruit = Banana;
id = 02;
}, {
fruit = Orange;
id = 03;
}
...它正在用数据填充动态表行。 我在行的右侧有一个重复的模板,带有一个UISwitch。
像这样:
如何定位特定的开关以打开或关闭,返回的项目打开?
我想我将需要存储添加到数据集中的ID数组。 例如
fruits = ["02","03"]
...并让代码查找具有该ID的行? 我对如何执行此操作感到有些困惑。
当加载视图时,我的最终结果将如下所示:
...取决于用户选择的内容。
任何帮助将不胜感激。
假设您的水果阵列中有这些水果-
[{
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数组。
希望对您有所帮助。
如果我们正在考虑您的数据一秒钟,您是否考虑过在Dictionary的每个项目中添加一些布尔类型的enable
属性。 因此,当用户点击单元格或切换此单元格时,您可以将此属性值从false
更改为true
,反之亦然。
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
而不是使用Dictionary,我将拥有一个引用类型的数据结构,例如一个class
,您可以在其中将字典转换为obj,反之亦然。 (不是必需的,但是它可以使您的生活更加轻松,当然,在保存或更新时,您可以将该对象转换为Dictionary)
class Item {
var id:Int
var fruit:String
var shouldBeEnabled:Bool
init(id:Int, fruit:String, enable:Bool = false) {
self.id = id
self.fruit = fruit
shouldBeEnabled = enable
}
// from dict to item
static func transform(dict:[String:Any]) -> Item {
var id = dict["id"] as! Int // use optional instead of explicit unwrapping
var fruit = dict["fruit"] as! String
var enabled = dict["enable"] as! Bool
return Item(id: id, fruit: fruit, enable: enabled)
}
// from item to dict
static func transform(item:Item) -> [String:Any] {
var dict = [String:Any]()
dict["id"] = item.id
dict["fruit"] = item.fruit
dict["enable"] = item.shouldBeEnabled
return dict
}
}
因此,下次用户进入您的应用程序时,开关的状态将保存为启用状态,然后填充tableView,然后应进行检查
consider you transform all your dict into object
if (data[indexPath.row].shouldBeEnabled == true) { // turn on switch }
else { // turn off }
现在,您的代码具有以下功能:保存用户的更改,并可以随时加载
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.