gpt4 book ai didi

ios - 如何在 Swift 中替换 ViewController?

转载 作者:搜寻专家 更新时间:2023-10-30 22:07:16 24 4
gpt4 key购买 nike

我已经使用这段代码展示了 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com