【问题标题】:How to prevent SegmentedControl index from changing, based upon confirmation dialog box?如何根据确认对话框防止 SegmentedControl 索引发生变化?
【发布时间】:2016-10-04 15:04:37
【问题描述】:

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

提前致谢。

【问题讨论】:

    标签: ios swift xcode uisegmentedcontrol


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      为了使开关看起来不错,我建议您将 lastSelectedIndex 存储在实例变量中,然后立即将所选索引设置为该值。只有当用户点击 Ok 时,您才进行实际的切换。

      查看下面的完整代码:

      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)
      }
      

      【讨论】:

      • 当然,在您进行验证之前,任何代码观察 (KVO) 这个 segmentControl 已经做出反应。此外,由于您立即使用self.segmentedControl.selectedSegmentIndex = lastSelectedIndex 重置选定的索引,因此如果用户稍后选择 OK,KVO 观察器将被触发两次,并且可能是第三次。
      猜你喜欢
      • 2011-03-25
      • 2012-04-04
      • 2020-03-20
      • 1970-01-01
      • 1970-01-01
      • 2011-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多