MG--Swift3.0導(dǎo)航欄的透明和顏色漸變


  • 0.效果圖采用(方法二)

    • 導(dǎo)航欄的透明和顏色漸變.gif

  • 1.擴(kuò)展

import UIKit

// MARK: - ??方法一
extension UINavigationBar {
    // MARK: - RunTime
    private struct NavigationBarKeys {
        static var overlayKey = "overlayKey"
    }
    
    var overlay: UIView? {
        get {
            return objc_getAssociatedObject(self, &NavigationBarKeys.overlayKey) as? UIView
        }
        set {
            objc_setAssociatedObject(self, &NavigationBarKeys.overlayKey, newValue as UIView?, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC
            )
        }
    }

    // MARK: - 接口
    func Mg_setBackgroundColor(backgroundColor: UIColor) {
        if overlay == nil {
            self.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
            overlay = UIView.init(frame: CGRect.init(x: 0, y: 0, width: bounds.width, height: bounds.height+20))
            overlay?.isUserInteractionEnabled = false
            overlay?.autoresizingMask = UIViewAutoresizing.flexibleWidth
        }
        overlay?.backgroundColor = backgroundColor
        subviews.first?.insertSubview(overlay!, at: 0)
    }
    
    
    func Mg_setTranslationY(translationY: CGFloat) {
        transform = CGAffineTransform.init(translationX: 0, y: translationY)
    }
    
    func Mg_setElementsAlpha(alpha: CGFloat) {
        for (_, element) in subviews.enumerated() {
            if element.isKind(of: NSClassFromString("UINavigationItemView") as! UIView.Type) ||
                element.isKind(of: NSClassFromString("UINavigationButton") as! UIButton.Type) ||
                element.isKind(of: NSClassFromString("UINavBarPrompt") as! UIView.Type)
            {
                element.alpha = alpha
            }
            
            if element.isKind(of: NSClassFromString("_UINavigationBarBackIndicatorView") as! UIView.Type) {
                element.alpha = element.alpha == 0 ? 0 : alpha
            }
        }
        
        items?.forEach({ (item) in
            if let titleView = item.titleView {
                titleView.alpha = alpha
            }
            for BBItems in [item.leftBarButtonItems, item.rightBarButtonItems] {
                BBItems?.forEach({ (barButtonItem) in
                    if let customView = barButtonItem.customView {
                        customView.alpha = alpha
                    }
                })
            }
        })
    }
    
    /// viewWillDisAppear調(diào)用
    func Mg_reset() {
        setBackgroundImage(nil, for: UIBarMetrics.default)
        overlay?.removeFromSuperview()
        overlay = nil
    }
}


// MARK: -
// MARK: -
// MARK: - ??方法二
extension UINavigationBar {
    // MARK: - 接口
    /**
     *  隱藏導(dǎo)航欄下的橫線,背景色置空 viewWillAppear調(diào)用
     */
    func star() {
        let shadowImg: UIImageView? = self.findNavLineImageViewOn(view: self)
        shadowImg?.isHidden = true
        self.backgroundColor = nil
    }
    
    /** 
     在func scrollViewDidScroll(_ scrollView: UIScrollView)調(diào)用
     @param color 最終顯示顏色
     @param scrollView 當(dāng)前滑動(dòng)視圖
     @param value 滑動(dòng)臨界值,依據(jù)需求設(shè)置
     */
    func change(_ color: UIColor, with scrollView: UIScrollView, andValue value: CGFloat) {
        if scrollView.contentOffset.y < -value{
            // 下拉時(shí)導(dǎo)航欄隱藏,無(wú)所謂,可以忽略
            self.isHidden = true
        } else {
            self.isHidden = false
            // 計(jì)算透明度
            let alpha: CGFloat = scrollView.contentOffset.y / value > 1.0 ? 1 : scrollView.contentOffset.y / value
            //設(shè)置一個(gè)顏色并轉(zhuǎn)化為圖片
            let image: UIImage? = imageFromColor(color: color.withAlphaComponent(alpha))
            self.setBackgroundImage(image, for: .default)
        }
    }
    
    /**
     *  還原導(dǎo)航欄  viewWillDisAppear調(diào)用
     */
    func reset() {
        let shadowImg = findNavLineImageViewOn(view: self)
        shadowImg?.isHidden = false
        self.setBackgroundImage(nil,for: .default)
    }
    
    
    // MARK: - 其他內(nèi)部方法
    //尋找導(dǎo)航欄下的橫線  (遞歸查詢(xún)導(dǎo)航欄下邊那條分割線)
    fileprivate func findNavLineImageViewOn(view: UIView) -> UIImageView? {
        if (view.isKind(of: UIImageView.classForCoder())  && view.bounds.size.height <= 1.0) {
             return view as? UIImageView
        }
        for subView in view.subviews {
            let imageView = findNavLineImageViewOn(view: subView)
            if imageView != nil {
                return imageView
            }
        }
        return nil
    }
    
    // 通過(guò)"UIColor"返回一張“UIImage”
    fileprivate func imageFromColor(color: UIColor) -> UIImage {
        //創(chuàng)建1像素區(qū)域并開(kāi)始圖片繪圖
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContext(rect.size)
        
        //創(chuàng)建畫(huà)板并填充顏色和區(qū)域
        let context = UIGraphicsGetCurrentContext()
        context!.setFillColor(color.cgColor)
        context!.fill(rect)
        
        //從畫(huà)板上獲取圖片并關(guān)閉圖片繪圖
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return image!
    }
}


  • 2.簡(jiǎn)單使用

  • 方法一: 簡(jiǎn)單使用(在控制器)

     func scrollViewDidScroll(_ scrollView: UIScrollView) {
         let color = UIColor(red: CGFloat(0 / 255.0), green: CGFloat(175 / 255.0), blue: CGFloat(240 / 255.0), alpha: CGFloat(1))
         let offsetY: CGFloat = scrollView.contentOffset.y
         if offsetY < 50 {
             let alpha: CGFloat = max(0, 1 - ((50 + 64 - offsetY) / 64))
             self.navigationController?.navigationBar.Mg_setBackgroundColor(backgroundColor: color.withAlphaComponent(alpha))
             titleLabel.textColor = UIColor.white
         } else {
             self.navigationController?.navigationBar.Mg_setBackgroundColor(backgroundColor: color.withAlphaComponent(1))
             titleLabel.textColor = UIColor.black
         }
     }
     override func viewWillAppear(_ animated: Bool) {
         super.viewWillAppear(animated)
         self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
         self.scrollViewDidScroll(collectionView)
     }
     override func viewWillDisappear(_ animated: Bool) {
         super.viewWillDisappear(animated)
         navigationController?.navigationBar.Mg_reset()
     }
  • 方法二:簡(jiǎn)單使用(在控制器)

   /// 方法二:簡(jiǎn)單使用
   func scrollViewDidScroll(_ scrollView: UIScrollView) {   
       self.navigationController?.navigationBar.change(UIColor.orange, with: scrollView, andValue: 64)
   }
   override func viewWillAppear(_ animated: Bool) {
       super.viewWillAppear(animated)
       self.navigationController?.navigationBar.star()
       scrollViewDidScroll(collectionView)
   }
   override func viewWillDisappear(_ animated: Bool) {
       super.viewWillDisappear(animated)
       self.navigationController?.navigationBar.reset()
   }

  • github

| 項(xiàng)目 | 簡(jiǎn)介 |
| : | : |
| MGDS_Swif | 逗視視頻直播 |
| MGMiaoBo | 喵播視頻直播 |
| MGDYZB | 斗魚(yú)視頻直播 |
| MGDemo | n多小功能合集 |
| MGBaisi | 高度仿寫(xiě)百思 |
| MGSinaWeibo | 高度仿寫(xiě)Sina |
| MGLoveFreshBeen | 一款電商App |
| MGWeChat | 小部分實(shí)現(xiàn)微信功能 |
| MGTrasitionPractice | 自定義轉(zhuǎn)場(chǎng)練習(xí) |
| DBFMDemo | 豆瓣電臺(tái) |
| MGPlayer | 一個(gè)播放視頻的Demo |
| MGCollectionView | 環(huán)形圖片排布以及花瓣形排布 |
| MGPuBuLiuDemo | 瀑布流--商品展 |
| MGSlideViewDemo | 一個(gè)簡(jiǎn)單點(diǎn)的側(cè)滑效果,仿QQ側(cè)滑 |
| MyResume | 一個(gè)展示自己個(gè)人簡(jiǎn)歷的Demo |
| GoodBookDemo | 好書(shū) |

Snip20161026_15.png

Snip20161026_16.png

Snip20161026_35.png
逗視介紹1.gif

逗視介紹2.gif

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

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