虽然我发现了类似的问题,但我无法理解它的答案。
我们如何读取 UISwitch
或 UITableViewCell
中任何元素的变化?尝试使用协议(protocol),但自定义单元类提示没有初始化程序。使用,一个委托(delegate),似乎不符合 View Controller 。
protocol SwitchTableViewCellDelegate {
func didChangeSwitchValue(value: Bool)
}
class SwitchTableViewCell: UITableViewCell {
var delegate: SwitchTableViewCellDelegate
var value: Bool = true
@IBOutlet weak var switchCellLabel: UILabel!
@IBOutlet weak var switchCellSwitch: UISwitch!
@IBAction func changedSwitchValue(sender: UISwitch) {
self.value = sender.on
delegate.didChangeSwitchValue(value)
}
在cellForRowAtIndexPath
中,
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! SwitchTableViewCell
cell.delegate = self
cell.switchCellLabel?.text = "Show Cloud Music"
cell.switchCellSwitch.on = userDefaults.boolForKey(cloudMusicKey)
关于如何实现这个有什么建议吗?
最佳答案
我建议为此使用 Swift 闭包。在您的单元格类中使用以下代码:
class SwitchTableViewCell: UITableViewCell {
var callback: ((switch: UISwitch) -> Void)?
var value: Bool = true
@IBOutlet weak var switchCellLabel: UILabel!
@IBOutlet weak var switchCellSwitch: UISwitch!
@IBAction func changedSwitchValue(sender: UISwitch) {
self.value = sender.on
callback?(switch: sender)
}
然后在您的 cellForRowAtIndexPath
中添加以下代码:
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! SwitchTableViewCell
cell.callback = { (switch) -> Void in
// DO stuff here.
}
cell.switchCellLabel?.text = "Show Cloud Music"
cell.switchCellSwitch.on = userDefaults.boolForKey(cloudMusicKey)
关于ios - 如何读取自定义 UITableViewCell 中 UISwitch 的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39893008/