如何点击UITableview中的所有其他开关,除了我点击的那个

时间:2018-03-22 10:40:30

标签: swift xcode9 uiswitch

我有一个包含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 个答案:

答案 0 :(得分:0)

你可以定义一个属性: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
}

并在Cell中:

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