UINavigationBar.setBackgroundImage 的动画无法正常工作

Animation for UINavigationBar.setBackgroundImage not working properly

我需要在某些时候更改 navBar 在我看来的背景图片,

let animation = CATransition()
override func viewDidLoad() {
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
    animation.type = kCATransitionFade
    animation.duration = 0.5
}

at scrollViewDidScroll() func 我应该更改 backgroundImage

override func scrollViewDidScroll() {
    if someCondition {
        showNavigationBar()
    } else {
        hideNavigationBar()
    }
}

func showNavigationBar() {
    self.navigationController?.navigationBar.layer.add(animation, forKey: nil)
    UIView.animate(withDuration: 0.4, animations: { 
        self.navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
        self.navigationController?.navigationBar.shadowImage = nil
    }, completion: nil)
    }
}

the problem is happening here the animation in this block didn't occur.However, while debugging the complier run this instruction, but there's no animation . :(

func hideNavigationBar() {
     UIView.animate(withDuration: 0.4, animations: {
        self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        self.navigationController?.navigationBar.shadowImage = UIImage()
    }, completion: nil)
    }
}

问题是什么,有什么想法吗?

我想出了如何做到这一点,我只是在 hideNavigationBar() 中添加了一行,显然在更改 navBar 背景图像后动画消失了。所以我只需要重新添加它':)

func hideNavigationBar() {
    self.navigationController?.navigationBar.layer.add(animation, forKey: nil)
    UIView.animate(withDuration: 0.4, animations: {
        self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        self.navigationController?.navigationBar.shadowImage = UIImage()
    }, completion: nil)
}