【问题标题】:How to read the changes in UISwitch in a custom UITableViewCell如何在自定义 UITableViewCell 中读取 UISwitch 中的更改
【发布时间】:2016-10-06 10:00:32
【问题描述】:

虽然我发现有人问过类似的问题,但我无法理解答案。

我们如何阅读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)
}

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)

有什么建议,关于如何实现这个?

【问题讨论】:

  • 展示你是如何实现委托回调的。
  • 实际上,我是 iOS 开发新手,正在尝试整理所有内容。不确定,如果这必须发生在cellForRowAtIndexPathdidSelectRowAtIndexPath..?
  • 显示cellForRowAtIndexPath的代码。
  • 按要求包含
  • @NiravD,谢谢.. 一切都解决了..

标签: ios swift uitableview uiswitch


【解决方案1】:

我建议为此使用 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)

【讨论】:

  • 那我就不需要委托了吗?
  • 不,你不需要委托,你可以像这样使用 Swift 闭包模式^^^。
  • 另外你不能调用变量switch,因为这是 Swift 中的保留关键字。
  • 太棒了!很高兴我能帮上忙。 :)
  • 可能我的问题很模糊! :/ cell.switchCellSwitch.enabled = false 做了我想要的...
【解决方案2】:

首先,由于可以有许多单元共享同一个委托,委托应该知道哪个单元调用它。因此,您的协议方法应该提供单元格本身,而不仅仅是它的开关值。实际上,我们可以省略开关值参数,因为它可以从单元格中查询到。

protocol SwitchTableViewCellDelegate {
    func switchTableViewCellDidChangeSwitchValue(cell: SwitchTableViewCell)
}

在你的委托的协议方法的实现中,你可以像这样访问开关值:

func switchTableViewCellDidChangeSwitchValue(cell: SwitchTableViewCell) {
    let switchValue = cell.value
}

其次,delegate 属性可以为 nil,因此其类型必须是 Optional

var delegate: SwitchTableViewCellDelegate?

value 更改时调用委托:

delegate?.switchTableViewCellDidChangeSwitchValue(self)

【讨论】:

  • 感谢您的建议。对于我当前的情况,我将关闭。它更简单..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-07
  • 2010-11-22
  • 1970-01-01
  • 1970-01-01
  • 2012-01-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多