ios - 如何读取自定义 UITableViewCell 中 UISwitch 的变化

标签 ios swift uitableview uiswitch

虽然我发现了类似的问题,但我无法理解它的答案。

我们如何读取 UISwitchUITableViewCell 中任何元素的变化?尝试使用协议(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/

相关文章:

ios - 如何在初始 viewDidLoad 周期后等待 subview 布局稳定下来?

ios - 知道来自 NSStream 的数据是完整的

swift - 从可选的通用扩展返回 nil

ios - 如何重新发送电子邮件验证 parse.com

ios - 观看连接无法正常工作

ios - iPad Split View Controller : Reloading the root view controller's tableview from the detail view controller

iphone - 无法更新 uitableview 行

iphone - NSArray 导致 EXC_BAD_ACCESS

objective-c - 只显示很少的cell时,是否需要实现可重用的UITableViewCells的出队机制?

ios - Xcode 中用于温度监控的仪器