【问题标题】:set OFF all UISwitches except current in tableViewCell将所有 UISwitches 设置为 OFF,除了 tableViewCell 中的当前 UISwitches
【发布时间】:2018-12-18 15:45:20
【问题描述】:

我需要用户能够从单元格中选择一个值。

@objc func switchChangedPeriod(_ sender : UISwitch!){
    if sender.isOn{
        periodUserString = period[sender.tag].periodUser
        periodSystemString = period[sender.tag].periodSystem
        //sender.setOn(false, animated: true) how to set OFF all switches except current
    }else{
        periodUserString = ""
        periodSystemString = ""
    }
}

或者我可能需要将之前的 UISwitch 设置为 OFF?

【问题讨论】:

  • 是否每个单元格都有开关,您想关闭除当前以外的所有开关吗?
  • 是的,除了当前的所有开关

标签: ios swift uitableview uiswitch


【解决方案1】:

首先为您的UITableViewCell 子类创建delegate,并在其值更改时声明switch 函数。

protocol CellDelegate {
    func switchChangedValue(_ value: Bool, period: Period)
}

现在在您的子类中创建 delegateperiod 变量,并在您的开关更改其值时创建 IBAction

class YourCell: UITableViewCell {

    var delegate: CellDelegate?
    var period: Period?
    ...
    @IBAction func switchChanged(_ sender: UISwitch) {
        delegate?.switchChangedValue(sender.isOn, period: period!)
    }
}

接下来让我们在控制器中为选定的Period 创建全局变量

var selectedPeriod: Period?

现在将您的委托实现为ViewController,并将periodUserStringperiodSystemString 设置为正确的格式,如果值为true,则将selectedPeriod 设置为period,如果开关关闭,请将其设置为@987654336 @。最后重新加载 TableView 的数据

class ViewController: UIViewController, CellDelegate {
    ...
    func switchChangedValue(_ value: Bool, period: Period) {
        periodUserString = value ? period.periodUser : ""
        periodSystemString = value ? period.periodSystem : ""
        selectedPeriod = value ? period : nil
        tableView.reloadData()
    }
}

...这里你应该考虑当你有selectedPeriod变量时是否需要设置periodUserStringperiodSystemString

现在在cellForRowAt 中设置UISwitch 状态取决于,如果selectedPeriod 等于索引等于indexPath.row 的数组中的某个period(请注意,现在您的Period 类/结构必须是可编码)。并且不要忘记设置单元格的delegateperiod

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    ... // cell as! YourCell
    cell.delegate = self
    let period = period[indexPath.row]
    cell.period = period
    cell.switch.setOn(period == selectedPeriod, animated: false)
    ...
}

【讨论】:

  • 不要使用标签。如果可以删除、插入或移动行,它们就会失败。有一些正确的方法可以在不使用标签的情况下获取索引路径。
  • @rmaddy 我只是想使用他的解决方案,更好的解决方案是使用委托模式。
  • 这是行不通的,因为一个单元格没有引用它的索引路径(它不应该)。
  • 我注意到了,但为时已晚
  • 您实际上比使用标签更糟糕。单元格永远不应该知道它的索引路径。如果行被删除、插入或移动,这将与使用标记一样错误。
猜你喜欢
  • 1970-01-01
  • 2011-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-24
  • 1970-01-01
相关资源
最近更新 更多