【发布时间】: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