UINavigationBar set custom shadow in AppDelegate.swift

放肆的年华 提交于 2019-12-07 02:06:06

问题


I want to set some shadow to the bottom of my UINavigationBar for the whole application. Here is what I've tried but it doesn't work:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    UINavigationBar.appearance().layer.shadowOffset = CGSizeMake(0, 3)
    UINavigationBar.appearance().layer.shadowRadius = 3.0
    UINavigationBar.appearance().layer.shadowColor = UIColor.yellowColor().CGColor
    UINavigationBar.appearance().layer.shadowOpacity = 0.7
}

Please, tell me how can I do this?

UPDATE: Solved by subclassing from UINavigationController

import UIKit

class ShadowUINavigationController: UINavigationController {

    override func viewWillAppear(animated: Bool) {
        let darkColor: CGColorRef = UIColor(hex: 0x212121).CGColor
        let lightColor: CGColorRef = UIColor.clearColor().CGColor
        let navigationBarBottom: CGFloat = self.navigationBar.frame.origin.y + self.navigationBar.frame.size.height + 20
        println(self.navigationBar.frame.origin.y)
        println(self.navigationBar.frame.size.height)
        println(navigationBarBottom)

        let newShadow: CAGradientLayer = CAGradientLayer()
        newShadow.frame = CGRectMake(0, navigationBarBottom, self.view.frame.size.width, 1)
        newShadow.colors = [darkColor, lightColor]
        self.view.layer.addSublayer(newShadow)
        super.viewWillAppear(animated)
    }
}

回答1:


A better solution by still using appearance and that does not require you to subclass the UINavigationBar and adding code to each navigation controller, would be:

Extend the UINavigationBar

extension UINavigationBar {

  var castShadow : String {
    get { return "anything fake" }
    set {
        self.layer.shadowOffset = CGSizeMake(0, 3)
        self.layer.shadowRadius = 3.0
        self.layer.shadowColor = UIColor.yellowColor().CGColor
        self.layer.shadowOpacity = 0.7

    }
  }

}

And add an app wide appearance rule (inside appdelegate "didFinishLaunchingWithOptions" for example)

UINavigationBar.appearance().castShadow = ""



回答2:


Easy, works on Swift 3:

    navigationController?.navigationBar.layer.shadowColor = UIColor.black.cgColor
    navigationController?.navigationBar.layer.shadowOpacity = 1
    navigationController?.navigationBar.layer.shadowOffset = CGSize.zero
    navigationController?.navigationBar.layer.shadowRadius = 10


来源:https://stackoverflow.com/questions/31756230/uinavigationbar-set-custom-shadow-in-appdelegate-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!