2017-06-28 90 views
0

我使用一個已知的動畫給我們所有人,動畫改變導航欄的背景圖片以延遲時間將其從半透明(我將其設置爲默認)改爲(藍色主題)。如何使用動畫更改導航欄的背景圖像?

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) 

但動畫沒有工作,但導航欄的背景圖像改變成功,我不知道爲什麼!

任何想法?

+0

沒有改變顏色的代碼你剛纔設置無圖像的背景圖像。 –

+0

@NiravD更新 –

回答

5

您需要在動畫塊內調用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) 
+0

謝謝,但沒有發生任何事情。 ':( –

+1

您是否需要更改'backgroundImage'或者您是否可以像上述示例代碼中那樣更改顏色?我現在還沒有時間進行調查,但這是針對此問題的明顯Objective-C解決方案更改圖像:https://stackoverflow.com/questions/10823068/how-can-i-animate-the-uinavigationbar-background-change-on-uiviewcontroller-push – Hodson

+0

'背景圖像',和其他答案與目標-C沒有工作! –