ios - 如何关闭一行上的一个开关并打开另一行上的另一个开关

标签 ios swift uitableview uiswitch

如何单击 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/

相关文章:

ios - 如何在 switch case(swift)中创建循环?

ios - 使用 Swift 从 Parse 表中查询昨天的记录

ios - 如何在ios中加载gif图像并控制它?

ios - 无法从collectionView中删除项目

objective-c - 使用 didSelectRowAtIndexPath 完成一些操作后如何取消选择 UITableViewCell?

ios - 如何在 GameOverScene 中从 GameViewController 调用方法

ios - 如何在一个 View Controller 中快速将占位符设置为多个 TextView

ios - 将导航栏后退按钮标题重置为默认 iOS

ios - 我可以在 Swift 中仅选择 UITableView 中一行的一部分可单击(可选择)吗?

objective-c - 将元素放入部分数组的大条件,更好的方法吗? - Objective-C