美文网首页
swift 导航栏滑动透明渐变

swift 导航栏滑动透明渐变

作者: 溪小希 | 来源:发表于2021-04-23 14:54 被阅读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
        }
    

    相关文章

      网友评论

          本文标题:swift 导航栏滑动透明渐变

          本文链接:https://www.haomeiwen.com/subject/myvcrltx.html