拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 允许在表格视图中仅选择一个选项切换按钮

允许在表格视图中仅选择一个选项切换按钮

白鹭 - 2022-01-24 2020 0 0

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

例如,如果我选择第二个选项 (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) {

  }
  

}

允许在表格视图中仅选择一个选项切换按钮

uj5u.com热心网友回复:

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

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()
}
标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *