9

按下某个控制器时,我正在更改导航栏的背景图像。我想动画化这种变化。我可以使用以下代码来做到这一点:

[UIView transitionWithView:self.navigationController.navigationBar
                  duration:0.3f
                   options:UIViewAnimationOptionTransitionCrossDissolve
                animations:^{
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"now-playing-nav-bar.png"]
                                                 forBarMetrics:UIBarMetricsDefault];
} completion:NULL];

但是,这会阻止应用到navigationBarTitleUIBarButtonItems 的默认推送动画。

如何让背景更改和推送动画协同工作?

我更喜欢香草的解决方案。

PS:我不能使用tintColor,因为背景是有纹理的。

4

3 回答 3

26

仅在 iOS 6 上测试

我使用核心动画解决了它:

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    CATransition *animation = [CATransition animation];
    animation.duration = 0.3;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animation.type = kCATransitionFade;

    [self.navigationController.navigationBar.layer addAnimation:animation forKey:nil];

    [UIView animateWithDuration:0.3 animations:^{
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"now-playing-nav-bar.png"] forBarMetrics:UIBarMetricsDefault];
    }];
}

做同样的事情viewWillDisappear:,你很高兴。

于 2013-02-25T17:18:19.637 回答
5

这适用于我在 iOS 9 上:

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    changeNavigationBackground()
}

func changeNavigationBackground() {
    // navigationBar should always exist if the view controller is in a UINavigationController
    guard let navigationBar = navigationController?.navigationBar else { return }

    // the current navigation background
    guard let imageView = navigationBar.subviews.filter({ $0 is UIImageView }).first else { return }
    let image = UIImage(named: "navigation_background")
    let newImageView = UIImageView(image: image)
    newImageView.frame = imageView.frame
    newImageView.alpha = 0.0
    navigationBar.insertSubview(newImageView, belowSubview: imageView)

    transitionCoordinator()?.animateAlongsideTransition({ (context) in
        imageView.alpha = 0.0
        newImageView.alpha = 1.0
    }, completion: { (context) in
        newImageView.removeFromSuperview()
        navigationBar.setBackgroundImage(image, forBarMetrics: .Default)
        imageView.alpha = 1.0
    })
}

如果可能,我会尽量避免使用 Core Animation,所以我只使用了视图并在过渡的同时更改了它们的 alpha 值。

于 2016-08-21T20:41:08.350 回答
0

没有过渡动画,推送动画是否有效?如果是,可能您需要在更改导航栏图像的块中自己制作推送动画。

于 2013-01-30T12:04:48.143 回答