如何根据确认对话框防止SegmentedControl索引发生变化?

问题描述:

我有一个SegmentedControl。当用户点击它时,会出现一个确认对话框,询问他们是否希望更改该值。如果他们点击“取消”,我想取消对SegmentedControl值的更改。如何根据确认对话框防止SegmentedControl索引发生变化?

这是一个代码段,我有:

@IBAction func indexChanged(_ sender: UISegmentedControl) { 
    let refreshAlert = UIAlertController(title: "Update", message: "Sure you wanna change this?", preferredStyle: UIAlertControllerStyle.alert) 

    refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in 

    })) 

    refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in 
     // Nothing 
    })) 

    present(refreshAlert, animated: true, completion: nil) 
} 

在此先感谢。

最好的办法是保持一个变量,它保存最后选择的索引。在取消的完成处理程序中,将分段的选定索引设置为变量的值。在Ok的完成处理程序中使用当前选定的索引更新变量。

为了开关看起来不错,我建议你存储在lastSelectedIndex一个实例变量,然后立即将所选择的指数为该值。只有当用户点击好吧,你做的实际开关。

请参见下面全码:

var lastSelectedIndex = 0 
@IBOutlet weak var segmentedControl: UISegmentedControl! 

@IBAction func indexChanged(_ sender: AnyObject) { 
    let newIndex = self.segmentedControl.selectedSegmentIndex; 
    self.segmentedControl.selectedSegmentIndex = lastSelectedIndex 

    let refreshAlert = UIAlertController(title: "Update", message: "Sure you wanna change this?", preferredStyle: .alert) 

    refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { [weak self, newIndex] (action: UIAlertAction!) in 
     self!.segmentedControl.selectedSegmentIndex = newIndex 
     self!.lastSelectedIndex = newIndex 
    })) 

    refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) 

    present(refreshAlert, animated: true, completion: nil) 
} 
+0

当然,任何代码观察(志愿)这个segmentControl已经反应,你可以做验证之前,但是。此外,由于您立即使用'self.segmentedControl.selectedSegmentIndex = lastSelectedIndex'重置所选索引,因此如果用户以后选择了OK,KVO观察者将被触发两次,并可能第三次触发。 – Yohst