我在我的应用程序中使用UISwitch
与valueChanged
目标,如下面的代码。这个开关在我的UITableView
settingsTableCell.androidSwitchSmall.addTarget(self, action: #selector(switchStateChanged(_:)), for: .valueChanged)
@objc func switchStateChanged(_ mjSwitch: MJMaterialSwitch) {
if self.lastSwitchState == mjSwitch.isOn {
return
}
self.lastSwitchState = mjSwitch.isOn
print(mjSwitch.isOn, mjSwitch.tag, "Small")
self.changeTrackStatus()
}
我正在改变目标方法中的Switch值。所以它再次调用switchStateChanged
方法。
但是我想只在用户改变开关状态时才调用switchStateChanged
这个方法。
什么是最好的方式。
我如何区分天气用户改变了开关状态或开关状态是以编程方式改变的。
按照步骤。
步骤1
在TabelView Cell
里面做一个变量
var Btn1 : (()->())?
第2步
在TabelViewCell
中创建UIButton的动作并在Variable
上面调用。
@IBAction func cellbtn(_ sender: UIButton) {
Btn1?()
}
第3步
在你的Bool
中声明一个Function
变量和你的View Controller
var IsSwitchOn = false
func switchStateChanged(_ mjSwitch: MJMaterialSwitch) {
if self.IsSwitchOn {
return
}
self.IsSwitchOn = True
print(mjSwitch.isOn, mjSwitch.tag, "Small")
self.changeTrackStatus()
}
第4步
在cellForRowAt indexPath
中调用此方法。
let cell = tableView.dequeueReusableCell(withIdentifier: "CellID") as! YourCell
cell.Btn1 = {
() in
Self.switchStateChanged()
}
希望这项工作。
您必须以编程方式发送操作,您可以使用以下扩展名
extension UISwitch {
func set(on state: Bool, animated: Bool = true) {
setOn(state, animated: animated)
sendActions(for: .valueChanged)
}
}
为什么不使用.touchUpInside。这只会在用户与交换机交互时触发选择器。
settingsTableCell.androidSwitchSmall.addTarget(self, action: #selector(switchStateChanged(_:)), for: .touchUpInside)