2016-03-03 45 views
0

我有一个UISwitch它执行一个操作。我需要显示带有/无选项的警报。如果用户选择选项,则不应发生任何情况。交换机的用户界面不应该改变。防止UISwitch改变UI状态

这是我的代码。

func toggleSwitchValueChanged(sender: UISwitch) { 
    let alert = UIAlertController(title: "", message: "This operation will reset the photos you have renamed already. Proceed?", preferredStyle: .Alert) 
    alert.addAction(UIAlertAction(title: "No", style: .Cancel) { action in 
     return 
    }) 
    alert.addAction(UIAlertAction(title: "Yes", style: .Default) { action in 
     self.api.includeCoverPhoto(sender.on) 
    }) 
    alert.preferredAction = alert.actions[1] 
    presentViewController(alert, animated: true, completion: nil) 
} 

我在UISwitch的值更改事件中触发此方法。

问题是如果我选择,操作不会继续。但UISwitch的用户界面已更改为另一个状态。

如何阻止这种情况的发生?

+0

你可以切换到默认状态,这就是我们通常做的。 –

+0

是的,'sender.setOn(!sender.on,animated:true)'确实有效,但我希望事先有办法阻止它,因为它看起来不太好。 – Isuru

回答

6
func toggleSwitchValueChanged(sender: UISwitch) { 
     let alert = UIAlertController(title: "", message: "This operation will reset the photos you have renamed already. Proceed?", preferredStyle: .Alert) 
     alert.addAction(UIAlertAction(title: "No", style: .Cancel) { action in 
      sender.setOn(true, animated:false)    
      return 
    }) 
    .... 
1

值改变操作方法被调用开关后发生了变化,所以你不能这样做的。

您需要禁用交换机的用户交互,然后在其上覆盖一个UIButton。根据你更喜欢的内容,在按钮的内部动作中提示你的警报,或者触摸按钮。

然后在您的按钮操作中,显示您的警报并以编程方式更改开关状态。

+0

有一个简单的解决方案,检查我的答案,它给了我很多问题,但它很简单:D – Markicevic

+0

您的解决方案不会停止切换状态更改,它只是在用户取消后更改状态。我的解决方案首先停止按钮改变状态。 –

0

如果你想在switchValueChanged改变switch.isOn参数只是这个

DispatchQueue.main.async { 
    self.switch.isOn = !sender.isOn // true or false 
}