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

问题描述 投票:0回答:1

如何点击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
    } 
}
ios swift uitableview uiswitch
1个回答
0
投票

无需每次都重新加载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委托调用

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    self.enableSwitchFor(indexPath: indexPath)
}
© www.soinside.com 2019 - 2024. All rights reserved.