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

Moh*_*ain 0 uinavigationbar uiviewanimation ios swift3

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

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)
Run Code Online (Sandbox Code Playgroud)

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

有任何想法吗?

Hod*_*son 7

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

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

更新以更改背景图像

这段代码对我有用:

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)
Run Code Online (Sandbox Code Playgroud)