【问题标题】:Perform segue after UIAlertController is dismissedUIAlertController 关闭后执行 segue
【发布时间】:2016-11-01 19:48:54
【问题描述】:

我过去在使用 UIAlertController 时也遇到过类似的问题,因为在 UIAlertController 被解除后 UI 线程上总是存在延迟。
我现在的问题是,如果用户单击“确定”UIAlertAction,我想执行一个转场,如果按下“取消”UIAlertAction,则什么也不会发生。
这是我的代码:

// create the uialertcontroller to display
let alert = UIAlertController(title: "Do you need help?",
                              message: "Would you like to look for a consultant?",
                              preferredStyle: .alert)
// add buttons
let okay = UIAlertAction(title: "Yes, please.", style: .default, handler: {_ in
    self.performSegue(withIdentifier: "segue", sender: nil)
})
let no = UIAlertAction(title: "No, I'm okay.", style: .cancel, handler: nil)
alert.addAction(okay)
alert.addAction(no)
self.present(alert, animated: true, completion: nil)

当前发生的情况是,当我点击“确定”时,segue 正在执行,但我只能看到过渡的最后时刻(即动画在 UIAlertController 被解除时开始)。
一旦UIAlertController 被解除,我如何让segue 开始?

注意 - 如果有其他方法,我不喜欢用 hacky 方法解决这个问题,比如在固定延迟后执行 segue。

谢谢!

【问题讨论】:

  • @matt 所以真的没有办法做到这一点,除非我在n 秒后制作动画?另外 - 我没有在哪里说禁止

标签: swift segue uialertcontroller


【解决方案1】:

问题出在这段代码中:

let okay = UIAlertAction(title: "Yes, please.", style: .default, handler: {_ in
    self.performSegue(withIdentifier: "segue", sender: nil)
})

handler: 不是 完成 处理程序。它在警报被(自动)解除之前运行。因此,当警报仍然存在时,您就开始了 segue。

如果您不想使用delay(尽管我认为这种方法没有任何问题),我会尝试这样:

let okay = UIAlertAction(title: "Yes, please.", style: .default, handler: {_ in
    CATransaction.setCompletionBlock({
        self.performSegue(withIdentifier: "segue", sender: nil)
    })
})

【讨论】:

  • 我想 - 在控制器被解雇后有什么方法可以执行此操作吗?
  • 我怎么告诉你不要这样做的?如果你指的是我的笔记,那只是意味着我当然更喜欢在时间之后没有静态调度的方法:)
  • 公平地说,我说的是一种 hacky 方法。我会争辩说,当有一个方法在某事发生后调用一个动作时,在硬编码的时间之后执行某事并不是一个好习惯。无论如何感谢您的帮助
  • 我不明白为什么一种方法比另一种方法或多或少“hacky”。无论哪种方式,您都在解决 API 的(奇怪)限制。任何时候你必须这样做,这都是一种黑客行为(也是 API 中的一个缺陷)。但这意味着您应该向 Apple 提交错误,而不是告诉我要给出什么样的答案。
  • 这是一个优雅的解决方案。我更喜欢这个而不是使用延迟。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多