驗證狀態切換的最佳或優雅方法是什么?
例如,如果我選擇第二個選項 (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()
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/398786.html
上一篇:在SwiftUI中初始化嵌套結構
下一篇:這個標簽欄控制器應該嵌入在哪里?
