iOS導(dǎo)航欄透明平滑過渡的簡單實(shí)現(xiàn)

iOS導(dǎo)航欄透明平滑過渡的簡單實(shí)現(xiàn)

前言

??項(xiàng)目中有時(shí)候需要某些導(dǎo)航欄看起來是透明的,但上面的item按鈕還是存在的,那么要怎么比較快速又簡單的實(shí)現(xiàn)呢?今天就來做個(gè)嘗試,供大家參考, 這里介紹是導(dǎo)航欄的測滑,UIScrollView的滑動(dòng)導(dǎo)航欄漸變也是一樣的道理,監(jiān)聽滑動(dòng)改變透明度即可。

導(dǎo)航欄透明

最簡單的導(dǎo)航欄透明只要這幾行代碼就可以實(shí)現(xiàn)

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

如果要取消透明,也很簡單

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

還有種手動(dòng)發(fā)改變透明度的方式

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

好了,透明的方式介紹完了,現(xiàn)在開始如何正確的使用(runtime魔法)

runtime處理UIViewController的導(dǎo)航欄透明

如果簡單的處理就是在需要透明的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
}

??每次如果都要這么寫估計(jì)要瘋,所以我們用runtime交換方法的實(shí)現(xiàn)來統(tǒng)一進(jìn)行處理, 這里需要知道swift下如何進(jìn)行swizzle method的方式, 詳細(xì)請(qǐng)看我的另一篇文章

swift下使用runtime交換方法的實(shí)現(xiàn)

交換viewwillappear的實(shí)現(xiàn)


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(){
       ///此方法的實(shí)現(xiàn)見 “swift下使用runtime交換方法的實(shí)現(xiàn)” 文章
        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) {

        //調(diào)用系統(tǒng)的
        prefix_viewWillAppear(animated)
        updateNavAlpha()
    }
    
    //抽出需要透明的控制器方法
    
    /// 需要導(dǎo)航欄透明的控制器
    ///
    /// - 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
        }
    }
}

這樣控制各種需要透明的控制器就比較方便了。

監(jiān)聽手勢的滑動(dòng)改變導(dǎo)航欄的透明度(平滑的過渡)

這里只要交換導(dǎo)航控制的 _updateInteractiveTransition:就能實(shí)現(xiàn)

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)
        }
        
    }
    
}

此刻用手滑動(dòng)可能會(huì)發(fā)現(xiàn)這樣的問題

問題

??這是由于控制器沒有在導(dǎo)航欄下導(dǎo)致到的效果,其實(shí)就是屬性extendedLayoutIncludesOpaqueBars作祟
只要在不需要透明的控制器中設(shè)置

extendedLayoutIncludesOpaqueBars = true

改造下剛才的方法

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

到這里大致能實(shí)現(xiàn)完整需求了,看起來大概是這個(gè)樣子

image

修復(fù)小瑕疵

1

因?yàn)槭窃趘iewwillappear中設(shè)置導(dǎo)航欄的透明度,所以push到下一個(gè)控制器的時(shí)候中間的跳變是比較明顯的,
簡單的做法就是, 做個(gè)動(dòng)畫讓透明度的變化不是直接跳變


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

如果這么做,導(dǎo)航欄的底部黑線的隱藏方式不能像網(wǎng)上一直認(rèn)為的寫法

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

在手勢滑動(dòng)過程中可能產(chǎn)生的小跳變解決

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)
            }
        }
        
    }
    
    
    
}

這里是最終的效果

最終效果

總結(jié)

??這是自己的一次嘗試導(dǎo)航欄隱藏的總結(jié),記錄下踩過的坑,最后發(fā)個(gè)寫的比較完全且比較牛的方案的鏈接

比較不錯(cuò)的導(dǎo)航欄透明

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容