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