【问题标题】:How do i turn off a switch on a row and turn on another one on another row如何关闭一行上的开关并打开另一行上的另一个开关
【发布时间】:2018-03-23 09:49:28
【问题描述】:

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

    无需每次都重新加载 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)
    }
    

    【讨论】:

    • 但是如果将委托和 tableView 出口分开,那么我将 tableView 放在一个类中,然后将出口放在我的 viewController 中?
    • 将此函数添加到您的 tableview 出口添加的文件中
    • 啊,但我知道 tableView 插座没有成员 answerSwitch
    • 因为 switch 在 tableviewcell 中。
    • 我该如何解决这个问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-24
    • 1970-01-01
    相关资源
    最近更新 更多