如何用动画更改导航栏的背景图片?

时间:2017-06-28 11:05:42

标签: ios swift3 uinavigationbar uiviewanimation

我正在使用我们所有人的已知动画,动画更改导航栏的背景图像,延迟时间将其从半透明(我将其设为默认值)更改为(蓝色主题)。

UIView.animate(withDuration:0.5, 
               delay: 0, 
               option: UIViewAnimationOptions.curveEaseOut, 
               animations: {
        self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        self.navigationController?.navigationBar.shadowImage = UIImage()
    }, completion: nil)

但动画没有用,但导航栏的背景图片改变成功,我不知道为什么!!

有什么想法吗?

1 个答案:

答案 0 :(得分:6)

您需要在动画块中调用layoutIfNeeded(),例如

UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseOut, animations: { 
    self.navigationController?.navigationBar.barTintColor = .blue
    self.navigationController?.navigationBar.layoutIfNeeded()
}, completion: nil)

更改背景图片的更新

此代码对我有用:

let animation = CATransition()
animation.duration = 0.5
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
animation.type = kCATransitionFade

navigationController?.navigationBar.layer.add(animation, forKey: nil)

UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseOut, animations: {
    self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: "your-image-name"), for: .default)
}, completion: nil)