展示一个视图控制器,关闭它并在 Swift 中展示一个不同的 [英] Present a view controller, dismiss it and present a different one in Swift

查看:22
本文介绍了展示一个视图控制器,关闭它并在 Swift 中展示一个不同的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个根视图控制器,它有一个按钮,当用户按下它时,会显示另一个视图控制器.

I have a root view controller that has a button that when the user pushes it, another view controller is presented.

第二个控制器有一个返回到根视图控制器的关闭选项和一个按钮,当用户触摸它时它关闭当前视图控制器,因此它会返回到根视图控制器一秒钟并呈现另一个.

This second controller has a dismiss option that just comes back to the root view controller and a button that when the user touches it dismisses the current view controller so it goes back to the root view controller for a second and presents another one.

转到我使用的第一个控制器:

Going to the first controller I use:

let vc = FirstController()
self.present(vc, animated: true, completion: nil)

当我在另一个视图控制器中选择只关闭的按钮时,我会这样做.

And when in the other view controller I select the button that only dismisses I do this.

self.dismiss(animated: true, completion: nil)

因此,对于需要关闭并呈现另一个控制器的第二个控制器,我尝试了以下操作:

So for the second controller that needs to dismiss and present another one I have tried the following:

self.dismiss(animated: true, completion: {
    let vc = SecondController()
    self.present(vc, animated: true, completion: nil)
})

但我收到一个错误:

警告:尝试呈现 <UINavigationController: 0xa40c790>在 <IIViewDeckController: 0xa843000>其视图不在窗口层次结构中!

Warning: Attempt to present <UINavigationController: 0xa40c790> on <IIViewDeckController: 0xa843000> whose view is not in the window hierarchy!

推荐答案

发生错误是因为您在关闭 FirstController 后试图从 FirstController 呈现 SecondController.这不起作用:

The error occurs because you are trying to present SecondController from FirstController after you have dismissed FirstController. This doesn't work:

self.dismiss(animated: true, completion: {
    let vc = SecondController()

    // 'self' refers to FirstController, but you have just dismissed
    //  FirstController! It's no longer in the view hierarchy!
    self.present(vc, animated: true, completion: nil)
})

这个问题非常类似于我的一个问题昨天回答.

This problem is very similar to a question I answered yesterday.

根据您的情况进行修改,我建议这样做:

Modified for your scenario, I would suggest this:

weak var pvc = self.presentingViewController

self.dismiss(animated: true, completion: {
    let vc = SecondController()
    pvc?.present(vc, animated: true, completion: nil)
})

这篇关于展示一个视图控制器,关闭它并在 Swift 中展示一个不同的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆