我正在尝试通过创建图层并将其作为子图层添加到导航栏来更改导航栏的背景。但是,这只会影响导航栏。
我不想影响整个屏幕的顶部。代码包括:
let navBarLayer = StyleUtils.createGradientLayerWithColors(color: StyleUtils.Colors.SKY_BLUE, frame: (self.navigationController?.navigationBar.bounds)!)
self.navigationController?.navigationBar.layer.addSublayer(navBarLayer)
createGradientLayerWithColors 函数返回给定帧的CAGradientLayer。
我错过了什么?提前谢谢。
修改
我试过纳撒尼尔的回答,但得到了这个:
值得一提的是,这也是一个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 :(得分:13)
这是我管理它的方式。
首先我将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
答案 1 :(得分: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)
这不是更好,只是另一种方式来做同样的事情。