UINavigationBar 在 AppDelegate.swift 中设置自定义阴影 [英] UINavigationBar set custom shadow in 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
}
请告诉我我该怎么做?
更新:通过从 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
}
}
}
并添加应用范围的外观规则(例如在 appdelegate "didFinishLaunchingWithOptions" 中)
And add an app wide appearance rule (inside appdelegate "didFinishLaunchingWithOptions" for example)
UINavigationBar.appearance().castShadow = ""
这篇关于UINavigationBar 在 AppDelegate.swift 中设置自定义阴影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!