2016-12-08 64 views
9

我試圖通過創建圖層並將其作爲子圖層添加到導航欄來更改導航欄的背景。但是,這隻影響導航欄。在導航欄和狀態欄上設置漸變

1

我wan't它影響屏幕的整個頂部。代碼包括:

let navBarLayer = StyleUtils.createGradientLayerWithColors(color: StyleUtils.Colors.SKY_BLUE, frame: (self.navigationController?.navigationBar.bounds)!) 

self.navigationController?.navigationBar.layer.addSublayer(navBarLayer) 

createGradientLayerWithColors函數返回給定的幀中的CAGradientLayer。

我錯過了什麼?先謝謝你。

編輯:

我試過納撒尼爾答案,但得到這個:

problem

值得一提的是,這也是一個TableView中。

SOLUTION:

,我發現這個question,幫助我解決了問題。

最後正確的代碼是:

func setNavBarColor() { 

    let navBar = self.navigationController?.navigationBar 

    //Make navigation bar transparent 
    navBar?.setBackgroundImage(UIImage(), for: .default) 
    navBar?.shadowImage = UIImage() 
    navBar?.isTranslucent = true 

    //Create View behind navigation bar and add gradient 
    let behindView = UIView(frame: CGRect(x: 0, y:0, width: UIApplication.shared.statusBarFrame.width, height: UIApplication.shared.statusBarFrame.height + (navBar?.frame.height)!)) 

    let layerTop = StyleUtils.createGradientLayerWithColors(color: StyleUtils.Colors.SKY_BLUE, frame: behindView.bounds) 
    behindView.layer.insertSublayer(layerTop, at: 0) 

    self.navigationController?.view.insertSubview(behindView, belowSubview: navBar!) 

} 
+0

我把這個方法放到UINavigationController的擴展中,叫做initializeNavBarStyle,它工作得很好! – LargeGlasses

回答

10

這是我如何管理它。

首先,我設置了導航欄,以透明:

self.navigationBar.setBackgroundImage(UIImage(), for: .default) 
self.navigationBar.shadowImage = UIImage() 
self.navigationBar.isTranslucent = true 
self.navigationBar.backgroundColor = UIColor.clear 

然後我的梯度添加到狀態欄和導航欄後面的觀點:

let gradient = CAGradientLayer() 
    gradient.frame = CGRect(x: 0, y: 0, width: UIApplication.sharedApplication().statusBarFrame.width, height: UIApplication.sharedApplication().statusBarFrame.height + self.navigationController!.navigationBar.frame.height) 
    gradient.locations = [0.0,1.0] 
    gradient.colors = [UIColor.anyColor().colorWithAlphaComponent(0.4).CGColor, UIColor.clearColor().CGColor] 
    self.view.layer.addSublayer(gradient) 
    self.view.backgroundColor = UIColor.clear 
+0

我試過你的答案,但它有一些問題。請檢查我的編輯。 Ps:我還用其他顏色進行了實驗。 – PablodeAcero

+0

@PablodeAcero我在NavigationBar透明部分的末尾添加了一行 - 試試! – Nathaniel

+1

嘿。您的評論沒有解決問題,但它幫助我搜索解決方案。非常感謝您的幫助!我會將此標記爲正確的答案,然後我會用答案更新我的問題。 – PablodeAcero

0

我的選項:

let gradientLayer = CAGradientLayer() 

let layerY = -UIApplication.shared.statusBarFrame.size.height as CGFloat 

let layerHeight = (self.navigationController?.navigationBar.frame.size.height)! + UIApplication.shared.statusBarFrame.size.height as CGFloat 

gradientLayer.frame = CGRect(x: 0, y: layerY, width: 1366, height: layerHeight) 

gradientLayer.colors = [UIColor(red: 16/255.0, green: 57/255.0, blue: 82/255.0, alpha: 1.0).cgColor, UIColor(red: 17/255.0, green: 132/255.0, blue: 157/255.0, alpha: 1.0).cgColor] 

self.navigationController?.navigationBar.layer.addSublayer(gradientLayer) 

這不是更好,只是另一種方式來做同樣的事情。