【发布时间】:2017-04-24 04:07:42
【问题描述】:
我正在尝试通过创建一个图层并将其作为子图层添加到导航栏来更改导航栏的背景。但是,这只会影响导航栏。
我不希望它影响整个屏幕顶部。包含的代码:
let navBarLayer = StyleUtils.createGradientLayerWithColors(color: StyleUtils.Colors.SKY_BLUE, frame: (self.navigationController?.navigationBar.bounds)!)
self.navigationController?.navigationBar.layer.addSublayer(navBarLayer)
createGradientLayerWithColors 函数返回给定帧的 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!)
}
【问题讨论】:
-
我把这个方法放到了UINavigationController的一个扩展里面,叫做initializeNavBarStyle,效果真的很好!
标签: ios swift uinavigationbar statusbar layer