如何根据确认对话框阻止SegmentedControl索引的更改?

时间:2016-10-03 12:42:50

标签: ios swift xcode uisegmentedcontrol

我有一个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)
}

提前致谢。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

为了使开关看起来不错,我建议你将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)
}