[iOS]巧妙的讓導航欄透明的懸浮在ViewController上
阿新 • • 發佈:2019-01-30
分享一個很簡單的讓系統的導航欄透明的懸浮在ViewController上效果,就幾行程式碼!
class SomeViewController : UIViewController { ... override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // self.edgesForExtendedLayout = .All // 要設定成全屏佈局才能看到效果,預設就是全屏的 // self.navigationController?.navigationBar.translucent = true // 必須開啟半透明效果,預設就是開啟的 let clearImage = UIImage.colorImage(UIColor.clearColor()) // 建立一個透明的圖片 self.navigationController?.navigationBar.setBackgroundImage(clearImage, forBarMetrics: .Default) self.navigationController?.navigationBar.shadowImage = clearImage } ... }
為了方便,擴充套件了一下 UIImage
//MARK:- 建立一個顏色圖片 extension UIImage { class func colorImage(color: UIColor) -> UIImage { return self.colorImage(color, size: CGSize(width: 2, height: 2)) } class func colorImage(color: UIColor, size: CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0) color.setFill() UIRectFillUsingBlendMode(CGRectMake(0, 0, size.width, size.height), kCGBlendModeXOR) let cgImage = CGBitmapContextCreateImage(UIGraphicsGetCurrentContext()) UIGraphicsEndImageContext() return UIImage(CGImage: cgImage)!.stretchableImageWithLeftCapWidth(1, topCapHeight: 1) } }
效果如下: