ios – 如何在Swift中替换ViewController?

ios – 如何在Swift中替换ViewController?,第1张

概述我使用以下代码呈现了ViewController1: let vc1 = ViewController1()present(vc1, animated: true, completion: nil) 现在,我想在ViewController1中显示ViewController2. @IBAction func buttonEvent(_ sender: UIButton) { let v 我使用以下代码呈现了VIEwController1:

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

现在,我想在VIEwController1中显示VIEwController2.

@IBAction func buttonEvent(_ sender: UIbutton) {    let vc2 = VIEwController2()    self.present(vc2,completion: nil)}

问题是:我想显示VIEwContoller2,而当调用按钮事件时,当前的VIEwController被解除.

这样做我想动画.

谢谢.

解决方法 您可以通过navigationController实现此目的,如下所示:

guard var vIEwControllers = sourceVIEwController.navigationController?.vIEwControllers else { return }// FIXME: Result of call to 'popLast()' is unused// Pop sourceVIEwControllervIEwControllers.popLast()// Push targetVIEwControllervIEwControllers.append(targetVIEwController)sourceVIEwController.navigationController?.setVIEwControllers(vIEwControllers,animated: true)

首先在导航堆栈中获取vIEwControllers.d出当前并追加目标.然后,将堆栈设置为更新的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),你应该通过presentVIEwController调用current()调用当前的.

weak var presentingVIEwController = self.presentingVIEwControllersourceVIEwController.dismiss(animated: true,completion: {    presentingVIEwController?.present(targetVIEwController,animated: false,completion: nil)})

虽然这次可能会看到转换,但在sourceVIEwController的dismiss()完成结束时,presentVIEwController将一直显示,直到targetVIEwController出现.我不知道你是否期望这种行为.如果不是,我现在无法提出解决方法来防止这种情况发生.

总结

以上是内存溢出为你收集整理的ios – 如何在Swift中替换ViewController?全部内容,希望文章能够帮你解决ios – 如何在Swift中替换ViewController?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1067103.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存