我有一个带5个标签的标签视图。我也有一个导航栏,并使用以下代码更改其背景颜色:
//Change navigation colors
viewController.navigationController?.navigationBar.barTintColor = UIColor.orange
viewController.navigationController?.navigationBar.tintColor = UIColor.white
viewController.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
Run Code Online (Sandbox Code Playgroud)
每个选项卡都有其自己的视图控制器,因此viewDidLoad(),我没有在方法中放入相同的代码,而是创建了一个UIHelper具有静态方法的类setupNavigation(viewController: UIViewController)。因此,在该:viewDidLoad()方法的每个viewController中,我只调用该方法
UIHelper.setupNavigation(viewController: self)
Run Code Online (Sandbox Code Playgroud)
有没有更简单的方法来更改导航栏背景的全局颜色?
我正在使用Swift 4。
编辑:其实我有一个MasterViewController选项卡的每个视图控制器扩展它。所以UIHelper.setupNavigation被称为MasterViewController的viewDidDLoad()。
您可以使用导航栏代理类(将设置转发到所有导航栏),例如在 AppDelegate 的方法 didFinishLaunchingWithOptions 中运行:
UINavigationBar.appearance().barTintColor = UIColor.orange
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
Run Code Online (Sandbox Code Playgroud)
您有很多方法可以做到这一点: 首先 创建一个superViewController,所有其他视图控制器都将继承此方法:
import UIKit
class SuperViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.barTintColor = UIColor.orange
self.navigationController?.navigationBar.tintColor = UIColor.white
self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Run Code Online (Sandbox Code Playgroud)
其他类似的视图控制器:
class ViewController: SuperViewController {
@IBOutlet weak var pageVC: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Run Code Online (Sandbox Code Playgroud)
现在,您无需在应用程序中设置导航颜色,只需在每个视图控制器中使用Inherit superViewcontroller。您可以添加将在每个控制器中遵循的所有常用方法。
第二种方法
///Common NavigationController for every controller used in application
class NavigationController: UINavigationController {
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.navigationBar.barTintColor = UIColor.red
self.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Run Code Online (Sandbox Code Playgroud)
在您应用中的任何地方使用此导航控制器。当您需要导航控制器时,请在导航控制器中提供此类。
| 归档时间: |
|
| 查看次数: |
2248 次 |
| 最近记录: |