ios - 在 UIAlert 之后执行 Segue

标签 ios swift

我正在尝试在确认警报后移动到下一个 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)
}

在 Storyboard上添加segue后,我成功地执行了segue,但是这会执行segue两次,一次是在按下"is"按钮时,另一次是在警报框中确认时。如果我删除 Storyboard 上的转场,则根本不会执行转场。我还尝试通过将按钮拖动到下一个 View Controller ,然后选择 custom 而不是 show 来创建自定义 Segue,但这给出了 SIGABRT错误。显然,在警报框中按下确认后,它应该只继续一次。

我在网上发现了类似的问题,但大多数似乎错过了 Storyboard的部分,我是否应该在两个 View 之间放置链接,还是应该全部以编程方式完成?如果仅以编程方式完成,我该如何识别下一个 View Controller ?

最佳答案

您可以通过编程方式实现此目的。在这种情况下,无需在 View Controller 之间放置链接。

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

If done programmatically exclusively, how am I supposed to identify the next view controller?

When you are moving from one screen to another screen there always will be destination view controller where you want to move. So you need to get that view controller from storyboard using self.storyboard.instantia(...) method

如何从 Storyboard获取 View Controller ?

您可以通过以下方式进行

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

如何设置 Storyboard ID 来查看 Controller ?

enter image description here

关于ios - 在 UIAlert 之后执行 Segue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54553460/

相关文章:

android - React Native Show <View> 使用循环

ios - Healthkit 隐私政策如何?

ios - 从 imagePicker 选择图像时,iOS11.2.6、Xcode 9.2 应用程序崩溃

ios - Swift 2 中的 messageComposeViewController 错误

swift - RxSwift 正确的方式

ios - 类型 "MyClass"不符合协议(protocol) "Collection_Delegate"

ios - 相同的代码在一个项目中有效,在另一个项目中无效

ios - 如何创建与 Alamofire 一起使用的 NTLM 身份验证 header ?

ios - Firebase 缓存过期总是和 Debug模式一样

ios - DidEnterRegion 仅在调用 requestAlwaysAuthorization 时调用。信标