在导航栏和状态栏上设置渐变

Setting gradient both on Navigation Bar and Status bar

我正在尝试通过创建图层并将其作为子图层添加到导航栏来更改导航栏的背景。但是,这只会影响导航栏。

我不希望它影响整个屏幕顶部。代码包括:

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

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

createGradientLayerWithColors 函数 returns 给定帧的 CAGradientLayer。

我错过了什么?提前谢谢你。

编辑:

我试过 Nathaniel 的回答,但得到了这个:

值得一提的是,这也是一个TableView。

解决方案:

我发现这个 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!)

}

我就是这样处理的。

首先我将 NavigationBar 设置为透明:

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

我的选择:

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)

它并没有更好,只是另一种方法。