UINavigationbar通过外观设置阴影不起作用

时间:2017-03-25 16:04:12

标签: ios swift swift3 uinavigationbar

我正在尝试向导航栏添加投影。代码如下所示:

UINavigationBar.appearance().barStyle = .black
UINavigationBar.appearance().barTintColor = UIColor(white: 155/255,
                                                    alpha: 1.0)
UINavigationBar.appearance().isTranslucent = false
UINavigationBar.appearance().layer.shadowOffset = CGSize(width: 0, height: 4)
UINavigationBar.appearance().layer.shadowRadius = 4.0
UINavigationBar.appearance().layer.shadowColor = UIColor.black.cgColor
UINavigationBar.appearance().layer.shadowOpacity = 0.4
UINavigationBar.appearance().layer.masksToBounds = false
UINavigationBar.appearance().layer.shouldRasterize = true

但它不起作用。为什么它不起作用,我错过了什么?我不想扩展或子类化NavigationBar来执行此操作。

编辑: 我想通了

UINavigationBar.appearance().layer.bounds

返回错误的值,所以可能就是这样,但有人知道为什么吗?

2 个答案:

答案 0 :(得分:0)

viewDidLoad

中尝试以下代码
    navigationController?.navigationBar.layer.shadowColor = UIColor.black.cgColor
    navigationController?.navigationBar.layer.shadowOpacity = 1
    navigationController?.navigationBar.layer.shadowOffset = CGSize.zero
    navigationController?.navigationBar.layer.shadowRadius = 10
    navigationController?.navigationBar.layer.masksToBounds = false

<强>输出:

enter image description here

答案 1 :(得分:0)

Swift 3

扩展UINavigationBar并定义所需的阴影属性

extension UINavigationBar {

    var shadow: Bool {
        get {
            return false
        }
        set {
            if newValue {
                self.layer.shadowOffset = CGSize(width: 0, height: 2)
                self.layer.shadowColor = UIColor.lightGray.cgColor
                self.layer.shadowRadius = 3
                self.layer.shadowOpacity = 0.5;
            }
        }
    }
}

AppDelegate的影子全局添加为

UINavigationBar.appearance().shadow = true

积分Amer Harb