ios - 如何在 Swift 中替换 ViewController?

标签 ios swift

我已经使用这段代码展示了 ViewController1:

let vc1 = ViewController1()
present(vc1, animated: true, completion: nil)

现在,我想在 ViewController1 中显示 ViewController2。

@IBAction func buttonEvent(_ sender: UIButton) {
    let vc2 = ViewController2()
    self.present(vc2, animated: true, completion: nil)
}

问题是:我想在调用按钮事件时关闭当前 ViewController 的同时显示 ViewContoller2。

我想在执行此操作时制作动画。

谢谢。

最佳答案

您可以通过 navigationController 实现这一点,如下所示:

guard var viewControllers = sourceViewController.navigationController?.viewControllers else { return }

// Popped ViewController not used
_ = viewControllers.popLast()

// Push targetViewController
viewControllers.append(targetViewController)

sourceViewController.navigationController?.setViewControllers(viewControllers, animated: true)

首先在导航堆栈中获取 viewControllers。弹出当前并附加目标之一。然后,将您的堆栈设置为更新的 viewControllers

添加

(对于那些不使用navigationController的人)

我意识到给定答案中可能存在问题。因此我想做这个补充。检查documentation of parent在继续之前。我想强调这部分:

If the recipient is a child of a container view controller, this property holds the view controller it is contained in. If the recipient has no parent, the value in this property is nil. Prior to iOS 5.0, if a view did not have a parent view controller and was being presented, the presenting view controller would be returned. On iOS 5, this behavior no longer occurs. Instead, use the presentingViewController property to access the presenting view controller.

简而言之,如果您想关闭当前的 UIViewController(sourceViewController)并显示下一个(targetViewController),您应该来自 presentingViewControllerpresent() 调用。

weak var presentingViewController = self.presentingViewController

sourceViewController.dismiss(animated: true, completion: {
    presentingViewController?.present(targetViewController, animated: false, completion: nil)
})

虽然这次您可能看到了转换,但在 sourceViewControllerdismiss()completion 结束时,presentingViewController 将一直显示到 targetViewController 出现为止。我不知道你是否期望这种行为。如果不是,我暂时无法想出解决方法来防止这种情况发生。

关于ios - 如何在 Swift 中替换 ViewController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47589260/

相关文章:

ios - 默认纵向,一些特殊的屏幕如何自动旋转或强制某些屏幕横向?

ios - 如何在 Swift 3 中将 edgesForExtendedLayout 设置为 none

ios - 我应该将核心数据与 REST API 后端一起使用吗?

ios - 如何播放epub文件中的视频?

swift - 向 tableview 单元格添加阴影会导致滚动滞后和重复阴影

ios - UIImage drawInRect 不按比例绘制

ios - Xamarin.ios 刷新按钮

objective-c - 项目未链接 (KissXML/iOS)

ios - 在 pod 部分编写代码时无法访问 AppDelegate 类

swift - 新项目使用 SwiftUI、XCode 12 和 Catalina 失败