在我的app委托中,我调用以下代码将每个VC的导航栏颜色设置为蓝色。但是,如果用户没有登录并只是将应用程序旋转,我希望导航栏为红色。
UINavigationBar.appearance().barTintColor = UIColor(red: 108.0/255.0, green: 158.0/255.0, blue: 236.0/255.0, alpha: 1.0) // Blue
// UINavigationBar.appearance().barTintColor = UIColor(red: 239.0/255.0, green: 119.0/255.0, blue: 97.0/255.0, alpha: 1.0) // Red
UINavigationBar.appearance().tintColor = .white
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white]
如何根据每个VC的用户选择更改颜色?
答案 0 :(得分:1)
以viewWillAppear
方式更改每个VC中的颜色
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
navigationController?.navigationBar.barTintColor = UIColor(red: 0/255.0, green: 210/255.0, blue: 255/255.0, alpha: 1.0)
}
如果您正在等待某些事件发生,那么您可能会在完成后更改。像这样
navigationController?.navigationBar.barTintColor = UIColor(red: 0/255.0, green: 210/255.0, blue: 255/255.0, alpha: 1.0)
答案 1 :(得分:0)
将UIViewController
的以下扩展名添加到您的项目中,请注意这是“在所有视图控制器上运行相同代码”的最简单,最直接的方法,但它使用方法调配 。虽然我在下面编写的代码非常安全,如果您不知道自己在做什么,它可能会导致意外/意外行为。 谨慎行事。
extension UIViewController {
public override class func initialize() {
struct Static {
static var token: dispatch_once_t = 0
}
// make sure this isn't a subclass
if self !== UIViewController.self {
return
}
dispatch_once(&Static.token) {
let originalSelector = Selector("viewWillAppear:")
let swizzledSelector = Selector("extended_viewWillAppear:")
let originalMethod = class_getInstanceMethod(self, originalSelector)
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
let didAddMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
if didAddMethod {
class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
} else {
method_exchangeImplementations(originalMethod, swizzledMethod)
}
}
}
func extended_viewWillAppear(animated: Bool) {
self.extended_viewWillAppear(animated)
// Call your code here that you want to run for all view controllers, table view controllers, tab view controllers etc...
navigationController?.navigationBar.barTintColor = UIColor(red: 0/255.0, green: 210/255.0, blue: 255/255.0, alpha: 1.0)
}
}