Swift 如何在 CoreData 模型中保存动态创建的 UISwitch 的更改状态?

How to save changed state of dynamic created UISwitch in CoreData model in Swift?

我有一个 UITableView 包含用户添加的动态单元格。每个单元格有一个 UILabel 和一个 UISwitch。开关的默认状态为 ON。每当用户添加这些值时,我都会将这些值保存在 CoreData 模型中(UILabel 作为字符串 & UISwitch 作为 Bool)。 我想 update/store 每当用户切换开关时,开关状态对应于 CoreData 模型中同一单元格中的标签值。我已将标签 (switch.tag = indexPath.row) 添加到行中的每个开关,并且可以通过在我的 cellChanged 函数中使用 sender.tag 来访问它。但是我无法获取已切换开关的那一行的标签。如果我能以某种方式获取与切换的开关对应的标签值,那么我可以 运行 一个 for 循环在 CoreData 模型中查找该标签值,然后设置 UISwitch 的状态。由于我使用的是 Swift 语言,如果您能使用相同的语言解释代码,我将不胜感激。

更好的模式可以是在单元格中创建协议。像

@protocol MyCellDelegate{
func cellSwitchChanged(forCell: MyCell, toValue: Bool, withLabel: String?)
}

class MyCell: UITableVeiwCell{
weak veer delegate: MyCellDelegate
.
.
.

@IBaction handleSwitchChanged(sender: UISwitch){
self.delegate?.cellSwitchChanged(forCell: self, toValue: sender.value, withLabel: self.lblName.text) 
}
}

并在您的单元格中为一行 indexPath,指定您 vc 成为该单元格的代表。并覆盖此方法。

所以每次开关改变时,视图控制器都会获取单元格引用、开关值和文本标签。然后你可以在这里做你的核心数据更新操作。

这对我有用:

func switchTapped(sender:UISwitch) {
let switchPosition = sender.convertPoint(CGPointZero, toView: self.tableView)
let indexPath = self.tableView.indexPathForRowAtPoint(switchPosition)

}