【问题标题】:Allows to choose only one option switch button inside table view只允许在表格视图中选择一个选项切换按钮
【发布时间】:2021-12-30 04:09:10
【问题描述】:

验证状态切换的最佳或优雅方式是什么?

例如,如果我选择第二个选项 (NO),则将第一个选项状态 (isOn 更改为 false) (SI)

我想实现只允许选择一个选项

我在表格视图中有这个开关

extension QuestionListTableViewCell: UITableViewDelegate, UITableViewDataSource {
  
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return answers.count
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "answerListCell", for: indexPath) as! AnswerListTableViewCell
    cell.separatorInset.right = cell.separatorInset.left
    cell.answerList.optionSwitch.tag = indexPath.row
    cell.answerList.optionSwitch.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)

    return cell
  }

  @objc func switchChanged(_ sender: UISwitch!){
    print("Table row switch Changed \(sender.tag)")
    print("The switch is \(sender.isOn ? "ON" : "OFF")")
  }
}

我从 xib 加载视图

class AnswerList: UIView {

  @IBOutlet weak var optionSwitch: UISwitch!
  @IBOutlet weak var optionLabel: UILabel!
  
  required init?(coder: NSCoder) {
    super.init(coder: coder)
    commonInit()
  }
  
  func commonInit(){
    let viewFromXib = Bundle.main.loadNibNamed("AnswerList", owner: self, options: nil)![0] as! UIView
    viewFromXib.frame = self.bounds
    addSubview(viewFromXib)
  }
  
  
  @IBAction func switchChangedState(_ sender: UISwitch) {

  }
  

}

【问题讨论】:

  • 您的 UI 不是数据的函数。我建议在数据模型中移动开关的状态当用户点击开关时,更改数据模型的状态并重新加载表。您可以通过仅重新加载必要的单元格来提高性能,但这应该可以帮助您入门。

标签: ios swift uitableview uiswitch


【解决方案1】:

您可能希望在视图控制器中添加一个属性来跟踪所选开关

var selectedSwitchIndex: Int?

并在您的cellForRowAt 方法中,将选定的开关设置为打开并保持其他开关关闭。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "answerListCell", for: indexPath) as! AnswerListTableViewCell
    cell.separatorInset.right = cell.separatorInset.left
    cell.answerList.optionSwitch.tag = indexPath.row
    cell.answerList.optionSwitch.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
    let isSelected = indexPath.row == selectedSwitchIndex
    cell.answerList.optionSwitch.isOn = isSelected

    return cell

在您的switchChanged 方法中,设置selectedSwitchIndex 属性以切换已切换的索引并重新加载您的表格视图。

@objc func switchChanged(_ sender: UISwitch!){
    // you would want to save the index only when its set to on
    guard sender.isOn else {
        // setting the selectedSwitchIndex to nil if the switch is turned off
        selectedSwitchIndex = nil
        return 
    }
    selectedSwitchIndex = sender.tag
    tableView.reloadData()
}

【讨论】:

    猜你喜欢
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-02
    • 2014-01-04
    • 2017-12-08
    • 2014-01-31
    • 1970-01-01
    相关资源
    最近更新 更多