如何单击 tableView 行,将行上的开关打开为绿色,然后当我单击下一行时,我想关闭最后一个开关并打开我单击的行上的开关?这是我迄今为止测试过的...
//the switch variable is located in a custom cell
var answerSwitch = UISwitch()
var previousSwitch = Bool()
var rowNumber = Int()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if(indexPath.row == rowNumber && cell.answerSwitch == false) {
cell.answerSwitch = true
} else if(indexPath.row == rowNumber && cell.answerSwitch == true) {
cell.answerSwitch = false
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if(previousSwitch == false) {
rowNumber = indexPath.row
tableView.reloadData()
previousSwitch = true
} else if(previousSwitch == true) {
tableView.reloadData
previousSwitch = false
}
}
最佳答案
无需每次都重新加载tableview。
在 UIViewController 中创造乐趣
var enabledSWitchRow: IndexPath = [0,0]
func enableSwitchFor(indexPath: IndexPath) {
//Already answered/on switch cell
let oldcell = tableView.cellForRow(at: enabledSWitchRow)
oldcell.answerSwitch.isOn = false
//selected cell
let newcell = tableView.cellForRow(at: indexPath)
newcell.answerSwitch.isOn = true
enabledSWitchRow = indexPath
}
并从 UITableView 的 didSelect 委托(delegate)调用
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.enableSwitchFor(indexPath: indexPath)
}
关于ios - 如何关闭一行上的一个开关并打开另一行上的另一个开关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49446708/