gpt4 book ai didi

swift - 转换到 UINavigationController 中嵌入的新 ViewController 会导致动画问题

转载 作者:行者123 更新时间:2023-11-28 07:33:30 28 4
gpt4 key购买 nike

我使用一个 rootViewController,我想移动到另一个 ViewController。向 newViewController 的过渡使用该代码。

当 newViewController 嵌入 UINavigationController 时出现问题。然后导航栏在动画期间动画并改变位置。

导航栏从左上角移动到正确的位置。

fileprivate func animateTransition(to newViewController: UIViewController) {
currentViewController.willMove(toParent: nil)
addChild(newViewController)
newViewController.view.frame = view.bounds
transition(from: currentViewController, to: newViewController, duration: 2, options: [.transitionCrossDissolve, .curveEaseOut], animations: {
self.currentViewController.removeFromParent()
newViewController.didMove(toParent: self)
self.currentViewController = newViewController
}, completion: nil)
}

如何使用“淡入淡出”动画移动到另一个 UINavigationController 以及导航栏如何从动画开始就处于正确位置?

最佳答案

首先,您应该将 View Controller 清理代码调用从 animations 闭包移动到 completion 闭包中:

currentViewController.willMove(toParent: nil)
addChild(newViewController)
newViewController.view.frame = view.bounds
transition(from: currentViewController, to: newViewController, duration: 2, options: [.transitionCrossDissolve, .curveEaseOut], animations: {
// this is intentionally blank
}, completion: { _ in
self.currentViewController.removeFromParent()
newViewController.didMove(toParent: self)
self.currentViewController = newViewController
})

您不希望在动画完成之前指示过渡已完成。

对于导航栏问题,与其让 transition(from:to:duration:...) 处理 View Controller 层次结构的操作,不如将其添加到 View 层次结构中,然后动画取消隐藏它。通常你会使用 .showHideTransitionViews 选项,但是 transition 仍然对混淆导航 Controller 的外观方法做一些奇怪的事情,所以最好自己制作动画:

currentViewController.willMove(toParent: nil)
addChild(newViewController)
newViewController.view.frame = view.bounds
newViewController.view.alpha = 0
view.addSubview(newViewController.view)
UIView.animate(withDuration: 2, delay: 0, options: .curveEaseOut, animations: {
newViewController.view.alpha = 1
}, completion: { _ in
self.currentViewController.view.removeFromSuperview()
self.currentViewController.removeFromParent()
newViewController.didMove(toParent: self)
self.currentViewController = newViewController
})

这将允许它从一开始就正确显示导航栏,然后淡入。

关于swift - 转换到 UINavigationController 中嵌入的新 ViewController 会导致动画问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53938210/

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