我有一个UITableView
,它有两个原型细胞,都有单独的TableViewCell
子类。在一个原型细胞里,我有多个开关。用户可以在表中选择他们想要的项目,并打开与该项目对应的开关。我希望能够存储UISwitch
状态,所以如果用户导航离开,回来,他们会看到他们之前选择了什么。
我试图将UISwitch
状态存储在字典中,然后在表重新加载时调用状态。
这是我到目前为止的代码:
@IBAction func switchState(sender: AnyObject) {
if mySwitch.on{
savedItems = NSMutableDictionary(object: mySwitch.on, forKey: "switchKey")
standardDefaults.setObject("On", forKey: "switchKey")
}
else{
standardDefaults.setObject("Off", forKey: "switchKey")
然后在awakeNib
部分:
override func awakeFromNib() {
super.awakeFromNib()
self.mySwitch.on = NSUserDefaults.standardUserDefaults().boolForKey("switchKey")
NSUserDefaults.standardUserDefaults().registerDefaults(["switchKey" : true])
}
谢谢你的帮助。
你需要做的是:
具有与数据源大小完全相同的字典(或任何其他数据类型)。
在你的
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
您需要为行indexPath.row
查找字典,然后mainpulate您的单元格
把我的答案放在这里而不是评论,这样我就可以更好地解释事情。您需要某种系统来跟踪哪个字典项对应于哪个UISwitch
。最好的方法可能是使用一个字典var uiDictionary = [String : Bool]()
,其中的键是一个字符串,您知道该字符串对应于特定的开关。然后,在cellForRowAtIndexPath:
中,您将尝试访问每个字典项,检查它是否为您试图设置的开关,然后设置它。我不知道你的确切设置,但它看起来像这样…
func cellForRowAtIndexPath() {
//other stuff here
//now set your switches
for (key, value) in uiDictionary {
switch(key) {
case "Switch1":
if value == true {
cell?.switch1.setOn(true, animated: true)
} else {
cell?.switch1.setOn(false, animated: true)
}
break
case "Switch2":
if value == true {
cell?.switch1.setOn(true, animated: true)
} else {
cell?.switch1.setOn(false, animated: true)
}
}
}
}