【问题标题】:Performing Segue after UIAlert在 UIAlert 之后执行 Segue
【发布时间】:2019-02-06 12:15:58
【问题描述】:

我正在尝试在确认警报后移至下一个 ViewController。

@IBAction func yesBtn(_ sender: Any) {
    let dialogMessage = UIAlertController(title: "Confirm", message: "Are you sure?", preferredStyle: .alert)

    let ok = UIAlertAction(title: "Confirm", style: .default, handler: { (action) -> Void in
        print("Ok button tapped")
        self.saveRecord(Answer: "yes")
        CATransaction.setCompletionBlock({
            self.performSegue(withIdentifier: "mainUse", sender: nil)
        })
    })

    let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (action) -> Void in
        print("Cancel button tapped")
    }

    //Add OK and Cancel button to dialog message
    dialogMessage.addAction(ok)
    dialogMessage.addAction(cancel)

    // Present dialog message to user
    self.present(dialogMessage, animated: true, completion: nil)
}

在情节提要上添加转场后,我设法执行转场,但是这会执行转场两次,一次是在按下是按钮时,另一次是在警报框中确认时。如果我删除情节提要上的转场,则根本不会执行转场。我还尝试通过将按钮拖动到下一个视图控制器然后选择custom 而不是show 来创建自定义segue,但这会产生SIGABRT 错误。显然,在警告框中按下确认后,它应该只进行一次。

我在网上发现了类似的问题,但大多数似乎都错过了故事板的部分,我应该在两个视图之间建立链接还是应该全部以编程方式完成?如果仅以编程方式完成,我应该如何识别下一个视图控制器?

【问题讨论】:

  • 确保您的 yesBtn 直接在 segue 中连接

标签: ios swift


【解决方案1】:

您可以通过编程实现此目的。在这种情况下,无需在视图控制器之间放置链接。

let ok = UIAlertAction(title: "Confirm", style: .default, handler: { (action) -> Void in

    let vc = self.storyboard.instan... //get the destination view controller
    self.navigationController.push(vc, animated: true) //or you can present it using self.present(...) method
})

如果仅以编程方式完成,我应该如何识别下一个视图控制器?

当您从一个屏幕移动到另一个屏幕时,总会有您想要移动的目标视图控制器。因此,您需要使用 self.storyboard.instantia(...) 方法从情节提要中获取该视图控制器

如何从情节提要中获取视图控制器?

你可以这样做

let destVC = UIStoryboard(name: "storyboard_name", bundle: nil).instantiateViewController(withIdentifier: "viewcontollerName_as_set_in_storyboard") as! DestinationViewController

如何将storyboard id设置为视图控制器?

【讨论】:

    【解决方案2】:

    为什么需要CATransaction?你自己不是在做动画。你不需要CATransaction,也不应该setCompletionBlock

    alert 和 segue 都有自己的动画。我怀疑您的完成块是在完成由它们触发的多个动画时触发的。

    如果您只想确保在主队列上执行操作,则可以改用 DispatchQueue.main.async

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多