Shy*_*yam 4 uitableview uiswitch ios swift
虽然我发现了类似的问题,但我无法理解它的答案.
UISwitch在一个UITableViewCell?中,我们如何阅读任何元素的变化?尝试使用协议,但自定义单元类抱怨没有初始化.使用,委托,似乎不符合视图控制器.
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)
}
Run Code Online (Sandbox Code Playgroud)
在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)
Run Code Online (Sandbox Code Playgroud)
关于如何实现这个的任何建议?
我建议使用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)
}
Run Code Online (Sandbox Code Playgroud)
那你的代码在你的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)
Run Code Online (Sandbox Code Playgroud)