swift 导航栏随着tableview的滑动的渐变效果

效果如图:

swift 导航栏随着tableview的滑动的渐变效果_第1张图片
rocky1.gif

之前做过用进行时实现过,但在跳转到另一个控制器,用手势返回的时候有bug
因此本文用自定义导航栏实现这个效果
废话说完 直接上代码

    /// 自定义导航栏
    private lazy var customNavigationBar = UIView()
    /// 自定义导航栏完全不透明时的偏移量边界(根据需求设定)
    private let alphaChangeBoundary = ScreenWidth * (212 / 375) - 64

在viewDidLoad中添加自定义导航栏
    customNavigationBar.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 64)
    customNavigationBar.backgroundColor = UIColor.colorWithHexString("#ff602f").colorWithAlphaComponent(0)
在viewWillAppear和viewWillDisappear方法中实现
        override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
 //界面将显示隐藏系统导航栏,添加自定义导航栏,防止从后面界面pop回此界面时导航栏显示有问题
        navigationController?.setNavigationBarHidden(true, animated: animated)
        navigationController?.view.insertSubview(customNavigationBar, atIndex: 1)
    }

    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        customNavigationBar.removeFromSuperview()
            //界面将要消失时,显示系统导航栏,移除自定义的导航栏
            self.navigationController?.setNavigationBarHidden(false, animated: false)
//调用此方法,解决滑动返回的bug  
            performSelectorOnMainThread(#selector(HomeViewController.delayHidden), withObject: animated, waitUntilDone: false)
}
    func delayHidden(animated: Bool) {
        self.navigationController?.setNavigationBarHidden(false, animated: false)
    }
实现颜色渐变的核心代码

在scrollview的代理方法中将offsetY与完全不透明时的偏移量alphaChangeBoundary作比较,进行颜色透明度的改变

override func scrollViewDidScroll(scrollView: UIScrollView) {
        let offsetY = scrollView.contentOffset.y
        if offsetY >= 0 && offsetY <= alphaChangeBoundary{
            customNavigationBar.backgroundColor = UIColor.colorWithHexString("#ff602f").colorWithAlphaComponent(offsetY / alphaChangeBoundary)
        }else if offsetY > alphaChangeBoundary {
            customNavigationBar.backgroundColor = UIColor.colorWithHexString("#ff602f")
        }else {
            customNavigationBar.backgroundColor = UIColor.colorWithHexString("#ff602f").colorWithAlphaComponent(0)
        }
        
        if offsetY < 0 {
            
            UIView.animateWithDuration(0.1, animations: {
                self.customNavigationBar.alpha = 0
            })
            
        }else{
            UIView.animateWithDuration(0.1, animations: {
                self.customNavigationBar.alpha = 1
            })
        }
    }

你可能感兴趣的:(swift 导航栏随着tableview的滑动的渐变效果)