如何用动画改变导航栏的背景图片?
How to change the background image of navigation bar with animation?
我正在使用我们所有人都知道的动画,以动画方式更改导航栏的背景图像,延迟很小,将其从半透明(我将其设置为默认)更改为(蓝色主题)。
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)
但是动画没有效果,但是导航栏的背景图改变成功了,不知道为什么!!
有什么想法吗?
您需要在动画块中调用 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)
我正在使用我们所有人都知道的动画,以动画方式更改导航栏的背景图像,延迟很小,将其从半透明(我将其设置为默认)更改为(蓝色主题)。
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)
但是动画没有效果,但是导航栏的背景图改变成功了,不知道为什么!!
有什么想法吗?
您需要在动画块中调用 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)