代码之家  ›  专栏  ›  技术社区  ›  J.Doe2

如何在UITableview中打开除单击的开关之外的所有其他开关

  •  0
  • J.Doe2  · 技术社区  · 6 年前

    我有一个包含UISwitch的tableView,我正在使用notificationCenter获取UISwitch的行。现在,我如何使用该信息关闭除我单击的开关之外的所有其他开关?

    func creatNotification()  {
        let switchNotification = Notification.Name("answer")
    
        NotificationCenter.default.addObserver(self,selector: #selector(getSwitchRow),name:switchNotification, object:nil)
    
    }
    @objc func getSwitchRow(notification: NSNotification){
        rowNumber = notification.object as! Int
        print("dataView2, getSwitchRow, rowNumber:", rowNumber)
    }  
    
    @IBAction func `switch`(_ sender: UISwitch) {
        var dataViewObject = DataView2()
        dataViewObject.creatNotification()
        let switchNotification = Notification.Name("answer")
        NotificationCenter.default.post(name: switchNotification, object: rowNumber)
    
        let switchNotification2 = Notification.Name("switch")
        NotificationCenter.default.post(name: switchNotification, object: answerSwitch.isOn)
    
        if(answerSwitch.isOn == true){
    
        }
    
    }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   JS_Coder    6 年前

    您可以定义一个属性:var previousSwitch:UISwitch?

    然后选择:

    @objc func setOn(sender: UISwitch,indexPath: IndexPath){
        if previousSwitch != nil {
            previousSwitch?.isOn = false
        }
        let sw = sender
        let isSetOn = sw.isOn
        if (isSetOn){
            print("on")
        }else{
            print("off")
        }
        previousSwitch = sw
    }
    

    和在单元格中:

    sw.addTarget(self, action: #selector(setOn(sender:indexPath:)), for: .valueChanged)
            cell?.contentView.addSubview(sw)