在swift中将阴影应用于导航栏

时间:2015-12-04 17:15:38

标签: ios swift

在我的设计导航应用程序有很好的阴影,我想在我的代码中应用。 如何创造这种效果?

enter image description here

5 个答案:

答案 0 :(得分:33)

不添加视图

self.navigationController?.navigationBar.layer.masksToBounds = false
self.navigationController?.navigationBar.layer.shadowColor = UIColor.lightGray.cgColor
self.navigationController?.navigationBar.layer.shadowOpacity = 0.8
self.navigationController?.navigationBar.layer.shadowOffset = CGSize(width: 0, height: 2.0)
self.navigationController?.navigationBar.layer.shadowRadius = 2

答案 1 :(得分:2)

我之前通过在导航栏下方添加了一个视图来完成此操作。

func addShadowToBar() {
    let shadowView = UIView(frame: self.navigationController!.navigationBar.frame)
    shadowView.backgroundColor = UIColor.whiteColor()
    shadowView.layer.masksToBounds = false
    shadowView.layer.shadowOpacity = 0.4 // your opacity
    shadowView.layer.shadowOffset = CGSize(width: 0, height: 2) // your offset
    shadowView.layer.shadowRadius =  4 //your radius
    self.view.addSubview(shadowView)
}

答案 2 :(得分:1)

斯威夫特3:

let shadowView = UIView(frame: navBar.frame)
shadowView.backgroundColor = UIColor.white
shadowView.layer.masksToBounds = false
shadowView.layer.shadowColor = UIColor.lightGray.cgColor
shadowView.layer.shadowOpacity = 0.8
shadowView.layer.shadowOffset = CGSize(width: 0, height: 2.0)
shadowView.layer.shadowRadius = 2
view.addSubview(shadowView)

答案 3 :(得分:1)

如果我没错,默认导航栏已经带有阴影。但是,如果您使用UIView制作自定义的,那么您应该这样做以使您的生活更轻松

yourView.clipsToBounds = false
yourView.layer.shadowOffset.height = 5 //this is your offset
yourView.layer.shadowOpacity = 0.25 //opacity of your shadow (recommended)

答案 4 :(得分:1)

    override func viewDidLoad() {
    super.viewDidLoad()

    self.navigationController?.navigationBar.layer.shadowColor = UIColor.black.cgColor
    self.navigationController?.navigationBar.layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
    self.navigationController?.navigationBar.layer.shadowRadius = 4.0
    self.navigationController?.navigationBar.layer.shadowOpacity = 1.0
    self.navigationController?.navigationBar.layer.masksToBounds = false
}