美文网首页iOS开发攻城狮的集散地程序员收藏ios
iOS导航栏透明平滑过渡的简单实现

iOS导航栏透明平滑过渡的简单实现

作者: 小峰书 | 来源:发表于2018-05-08 09:31 被阅读77次

    iOS导航栏透明平滑过渡的简单实现

    前言

      项目中有时候需要某些导航栏看起来是透明的,但上面的item按钮还是存在的,那么要怎么比较快速又简单的实现呢?今天就来做个尝试,供大家参考, 这里介绍是导航栏的测滑,UIScrollView的滑动导航栏渐变也是一样的道理,监听滑动改变透明度即可。

    导航栏透明

    最简单的导航栏透明只要这几行代码就可以实现

    navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
    navigationController?.navigationBar.shadowImage = UIImage()
    

    如果要取消透明,也很简单

    navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
    navigationController?.navigationBar.shadowImage = nil
    

    还有种手动发改变透明度的方式

    extension UINavigationController{
        
         func setBackgroundAlpha(alpha:CGFloat){
            if let barBackgroundView = navigationBar.subviews.first{
                if #available(iOS 11.0, *){
                    if navigationBar.isTranslucent{
                        for view in barBackgroundView.subviews {
                            view.alpha = alpha
                        }
                    }else{
                        barBackgroundView.alpha = alpha
                    }
                } else {
                    barBackgroundView.alpha = alpha
                }
            }
        }
    }
    
    

    这里可以给控制器添加属性方便直接修改

    private var navBarAlpha: Void?
    extension UIViewController{
    
        // navigationBar _UIBarBackground alpha
        var navBarBackgroundAlpha:CGFloat {
            get {
                guard let barBackgroundAlpha = objc_getAssociatedObject(self, &navBarAlpha) as? CGFloat else {
                    return 1.0
                }
                return barBackgroundAlpha
            }
            set {
                objc_setAssociatedObject(self, &navBarAlpha, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
                navigationController?.setBackgroundAlpha(alpha: newValue)
            }
        }
    }
    

    完成之后看起开是这样子的

    image

    好了,透明的方式介绍完了,现在开始如何正确的使用(runtime魔法)

    runtime处理UIViewController的导航栏透明

    如果简单的处理就是在需要透明的UIViewController中添加如下代码即可:

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //在这里处理透明 
        navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        navigationController?.navigationBar.shadowImage = UIImage()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
        navigationController?.navigationBar.shadowImage = nil
    }
    
    

      每次如果都要这么写估计要疯,所以我们用runtime交换方法的实现来统一进行处理, 这里需要知道swift下如何进行swizzle method的方式, 详细请看我的另一篇文章

    swift下使用runtime交换方法的实现

    交换viewwillappear的实现

    
    extension UIViewController{
        
        func navigationBarTransparency() {
            navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
            navigationController?.navigationBar.shadowImage = UIImage()
        }
        
        
        func navigationBarUnTransparency() {
            navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
            navigationController?.navigationBar.shadowImage = nil
        }
      
      
        public static func hook(){
           ///此方法的实现见 “swift下使用runtime交换方法的实现” 文章
            DispatchQueue.once(token: onceToken)
            {
                let needSwizzleSelectorArr = [
                    #selector(viewWillAppear(_:))
                ]
                
                for selector in needSwizzleSelectorArr {
                    let str = ("prefix_" + selector.description)
                    if let originalMethod = class_getInstanceMethod(self, selector),
                       let swizzledMethod = class_getInstanceMethod(self, Selector(str)) {
                        method_exchangeImplementations(originalMethod, swizzledMethod)
                    }
                }
            }
        }
        
        @objc private func prefix_viewWillAppear(_ animated: Bool) {
    
            //调用系统的
            prefix_viewWillAppear(animated)
            updateNavAlpha()
        }
        
        //抽出需要透明的控制器方法
        
        /// 需要导航栏透明的控制器
        ///
        /// - Returns: bool
        fileprivate func needOpacity() -> Bool{
            return self.isKind(of: OneViewController.self) ||
                   self.isKind(of: TwoViewController.self)
        }
        
        private func updateNavAlpha()  {
            if needOpacity(){
                navBarBackgroundAlpha = 0.0
            }else{
                navBarBackgroundAlpha = 1.0
            }
        }
    }
    

    这样控制各种需要透明的控制器就比较方便了。

    监听手势的滑动改变导航栏的透明度(平滑的过渡)

    这里只要交换导航控制的 _updateInteractiveTransition:就能实现

    extension UINavigationController{
        
        public static func injectHook() 
            guard self === UINavigationController.self else { return }
            DispatchQueue.once(token: "com.moglo.hallo.UINavigationController") {
                swizzle()
            }
            
        }
        
        private static func swizzle(){
            let needSwizzleSelectorArr = [
                NSSelectorFromString("_updateInteractiveTransition:")
            ]
            
            for selector in needSwizzleSelectorArr {
                let str = ("prefix_" + selector.description)
                if let originalMethod = class_getInstanceMethod(self, selector),
                   let swizzledMethod = class_getInstanceMethod(self, Selector(str)) {
                    method_exchangeImplementations(originalMethod, swizzledMethod)
                }
            }
        }
    
        @objc private func prefix_updateInteractiveTransition(_ percentComplete: CGFloat){
            
            prefix_updateInteractiveTransition(percentComplete)
    
            if let topVc = topViewController{
                let fromAlpha = topVc.transitionCoordinator?.viewController(forKey: .from)?.navBarBackgroundAlpha ?? 1.0
                let toAlpha = topVc.transitionCoordinator?.viewController(forKey: .to)?.navBarBackgroundAlpha ?? 0.0
                let nowAlpha = fromAlpha + (toAlpha - fromAlpha) * percentComplete
    //            Console.debug("----------fromAlpha:\(fromAlpha) -- toAlpha:\(toAlpha) -- nowAlpha:\(nowAlpha)")
                setBackgroundAlpha(alpha: nowAlpha)
            }
            
        }
        
    }
    

    此刻用手滑动可能会发现这样的问题

    问题

      这是由于控制器没有在导航栏下导致到的效果,其实就是属性extendedLayoutIncludesOpaqueBars作祟
    只要在不需要透明的控制器中设置

    extendedLayoutIncludesOpaqueBars = true
    

    改造下刚才的方法

    private func updateNavAlpha()  {
        if needOpacity(){
            navBarBackgroundAlpha = 0.0
        }else{
            extendedLayoutIncludesOpaqueBars = true
            navBarBackgroundAlpha = 1.0
        }
    }
    

    到这里大致能实现完整需求了,看起来大概是这个样子

    image

    修复小瑕疵

    1

    因为是在viewwillappear中设置导航栏的透明度,所以push到下一个控制器的时候中间的跳变是比较明显的,
    简单的做法就是, 做个动画让透明度的变化不是直接跳变

    
    UIView.animate(withDuration: 0.25, animations: {
        self.navgationBarAlpha = 0.0
    }) { (finished) in
        
    }
    

    如果这么做,导航栏的底部黑线的隐藏方式不能像网上一直认为的写法

    navigationBar.clipsToBounds = alpha == 0
    

    所以这里介绍正确的隐藏方式

    extension UINavigationController{
        
        var hairLineView: UIImageView? {
            get {
                return objc_getAssociatedObject(self, &hairLine) as? UIImageView
            }
            set {
                objc_setAssociatedObject(self, &hairLine, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
        }
        
        
        ///查找分割线
        public func findHairLine(view: UIView) -> UIImageView?{
            
            if view.isKind(of: UIImageView.self) && view.frame.size.height <= 1.0{
                return view as? UIImageView
            }
            
            for subView in view.subviews {
                let imageView = findHairLine(view: subView)
                if let imageView = imageView{
                    return imageView
                }
            }
            
            return nil
            
        }
        
        
        public func setHairLine(hidden: Bool){
            if let hairLineView = hairLineView{
                hairLineView.isHidden = hidden
            }else{
                hairLineView = findHairLine(view: navigationBar)
                hairLineView?.isHidden = hidden
            }
        }
        
    }
    

    在上述的setBackgroundAlpha变成

    func setBackgroundAlpha(alpha:CGFloat){
        if let barBackgroundView = navigationBar.subviews.first{
            if #available(iOS 11.0, *){
                if navigationBar.isTranslucent{
                    for view in barBackgroundView.subviews {
                        view.alpha = alpha
                    }
                }else{
                    barBackgroundView.alpha = alpha
                }
            } else {
                barBackgroundView.alpha = alpha
            }
        }
            let hidden = alpha == 0
            setHairLine(hidden: hidden)
    }
    

    2

    在手势滑动过程中可能产生的小跳变解决

    extension UINavgationController: UInavigationControllerDelegate{
        
        
            public func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
            
            if let topVC = topViewController,
                let coor = topVC.transitionCoordinator, coor.initiallyInteractive {
                if #available(iOS 10.0, *) {
                    coor.notifyWhenInteractionChanges({[weak self] (context) in
                        self?.dealInteractionChanges(context)
                    })
                } else {
                    coor.notifyWhenInteractionEnds({[weak self] (context) in
                        self?.dealInteractionChanges(context)
                    })
                }
            }
            
            
        }
        
        
        private func dealInteractionChanges(_ context: UIViewControllerTransitionCoordinatorContext){
            
            if context.isCancelled{
                let cancelDuration = context.transitionDuration * TimeInterval(context.percentComplete)
                let fromVc = context.viewController(forKey: .from)
                let nowAlpha = fromVc?.navBarBackgroundAlpha ?? 1.0
                UIView.animate(withDuration: cancelDuration) {[weak self] in
                    self?.setBackgroundAlpha(alpha: nowAlpha)
                }
            }else{
                let finishDuration = context.transitionDuration * TimeInterval(1 - context.percentComplete)
                UIView.animate(withDuration: finishDuration) {[weak self] in
                    let nowAlpha = context.viewController(forKey: .to)?.navBarBackgroundAlpha ?? 1.0
                    self?.setBackgroundAlpha(alpha: nowAlpha)
                }
            }
            
        }
        
        
        
    }
    
    

    这里是最终的效果

    最终效果

    总结

      这是自己的一次尝试导航栏隐藏的总结,记录下踩过的坑,最后发个写的比较完全且比较牛的方案的链接

    比较不错的导航栏透明

    相关文章

      网友评论

        本文标题:iOS导航栏透明平滑过渡的简单实现

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