swift 导航栏滑动透明渐变
2021-04-23 本文已影响0人
溪小希
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.alpha = 0.0
// 防止APP后台运行, 再进入前台, 上方出现一块空白
self.navigationController?.navigationBar.isTranslucent = true
// 当APP从后台进入前台, 根据 scrollView 的 contentOffset 设置导航栏透明度
NotificationCenter.default.addObserver(self, selector: #selector(becomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// 防止进入其他页面导航栏展示异常
self.navigationController?.navigationBar.alpha = 1.0
self.navigationController?.navigationBar.isTranslucent = false
}
// APP 从后台进入前台, 改变导航栏透明度
@objc func becomeActive() {
self.setAlpha()
}
// scrollView滑动 改变导航栏透明度
func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.setAlpha()
}
func setAlpha() {
let offsetY = scroll.contentOffset.y
let alpha = 1 - (kNavBarAndStatusBarHeight - offsetY) / kNavBarAndStatusBarHeight
self.navigationController?.navigationBar.alpha = alpha
}