UINavigationBar在AppDelegate.swift中设置自定义阴影 [英] UINavigationBar set custom shadow in AppDelegate.swift

查看:234
本文介绍了UINavigationBar在AppDelegate.swift中设置自定义阴影的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在整个应用程序的UINavigationBar底部设置一些阴影。这是我尝试过但它不起作用:

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
}

请告诉我该怎么办?

UPDATE:
通过UINavigationController的子类解决

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)
    }
}


推荐答案

仍然使用更好的解决方案外观并且不需要您子类化UINavigationBar并向每个导航控制器添加代码,如下:

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:

扩展UINavigationBar

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

    }
  }

}

并添加应用程序范围外观规则(例如在appdelegatedidFinishLaunchingWithOptions内)

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

UINavigationBar.appearance().castShadow = ""

这篇关于UINavigationBar在AppDelegate.swift中设置自定义阴影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆