【发布时间】:2018-01-26 04:31:13
【问题描述】:
我想在具有不同UINavigationBar 背景颜色的视图之间实现平滑动画。嵌入式视图具有与UINavigationBar 相同的背景颜色,我想模仿推/弹出过渡动画,例如:
我已经准备好自定义过渡:
class CustomTransition: NSObject, UIViewControllerAnimatedTransitioning {
private let duration: TimeInterval
private let isPresenting: Bool
init(duration: TimeInterval = 1.0, isPresenting: Bool) {
self.duration = duration
self.isPresenting = isPresenting
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return duration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let container = transitionContext.containerView
guard
let toVC = transitionContext.viewController(forKey: .to),
let fromVC = transitionContext.viewController(forKey: .from),
let toView = transitionContext.view(forKey: .to),
let fromView = transitionContext.view(forKey: .from)
else {
return
}
let rightTranslation = CGAffineTransform(translationX: container.frame.width, y: 0)
let leftTranslation = CGAffineTransform(translationX: -container.frame.width, y: 0)
toView.transform = isPresenting ? rightTranslation : leftTranslation
container.addSubview(toView)
container.addSubview(fromView)
fromVC.navigationController?.navigationBar.backgroundColor = .clear
fromVC.navigationController?.navigationBar.setBackgroundImage(UIImage.fromColor(color: .clear), for: .default)
UIView.animate(
withDuration: self.duration,
animations: {
fromVC.view.transform = self.isPresenting ? leftTranslation :rightTranslation
toVC.view.transform = .identity
},
completion: { _ in
fromView.transform = .identity
toVC.navigationController?.navigationBar.setBackgroundImage(
UIImage.fromColor(color: self.isPresenting ? .yellow : .lightGray),
for: .default
)
transitionContext.completeTransition(true)
}
)
}
}
并在UINavigationControllerDelegate方法实现中返回:
func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return CustomTransition(isPresenting: operation == .push)
}
虽然 push 动画效果很好,但 pop 却不行。
问题:
- 为什么在弹出动画之前清除 NavBar 颜色后仍然是黄色?
- 有没有更好的方法来实现我的目标? (导航栏不能一直透明,因为它只是流程的一部分)
这是我在 GitHub 上的测试项目的 link。
编辑
这是一个 gif,展示了所讨论问题的全貌和预期效果:
【问题讨论】:
-
嗨..您是否尝试在每个控制器的 viewWillAppear 中更改导航颜色?
-
@TomaszRejdych:我正在努力避免这种依赖:)
-
@CodeHunterr:是的,试过了,但没有得到肯定的结果。
-
hi @Fayer ..apple 默认动画对我的上述方法很有用。只需删除您的自定义动画并添加简单的 pushViewController 并返回 popViewController。它可能会帮助你取得好成绩。
标签: ios swift uinavigationbar custom-transition