我现在在我的应用程序中为我的5个标签栏项目提供了5个视图控制器。每个视图控制器都有相同的样式,只是标题不同。
这是我在所有这些视图控制器中单独使用的函数,并在viewDidLoad()中调用该函数
private func setupNavBar() {
let navBar = navigationController?.navigationBar
navBar?.prefersLargeTitles = true
navigationItem.title = "Library"
navigationItem.rightBarButtonItem?.tintColor = .white
navBar?.backgroundColor = UIColor.rgb(red: 10, green: 10, blue: 10)
navBar?.largeTitleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
navBar?.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
navBar?.setBackgroundImage(UIImage(), for: .default)
navBar?.shadowImage = UIImage()
}
我不想在每个VC中都这样做。相反,我想调用如下函数
setupNavBar(with largeTitles: Bool, has title: String)
我试图创建一个新的文件Functions.swift并将代码添加为一个函数,但是我得到的错误为navigationContoller,navigationBar,navigationItem为未定义
答案 0 :(得分:1)
您可以这样在UIViewController
上创建扩展名:
extension UIViewController {
public func setupNavBar(with largeTitles: Bool, has title: String) {
let navBar = navigationController?.navigationBar
navBar?.prefersLargeTitles = largeTitles
navigationItem.title = title
navigationItem.rightBarButtonItem?.tintColor = .white
navBar?.backgroundColor = UIColor(red: 10/255, green: 10/255, blue: 10/255, alpha: 1)
navBar?.largeTitleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
navBar?.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
navBar?.setBackgroundImage(UIImage(), for: .default)
navBar?.shadowImage = UIImage()
}
}
然后您可以从任何视图控制器内部这样调用它:
self.setupNavBar(with: false, has: "Check")
我倾向于使用UIViewController
扩展名,因为您实际上是在设置视图控制器本身的样式,因此可以向其中添加各种其他设置代码。
答案 1 :(得分:0)
class Functions: NSObject {
public static func setupNavBar(largeTitles: Bool, title: String, viewController: UIViewController?) {
guard let viewController = viewController else { return }
viewController.navigationController?.navigationBar.prefersLargeTitles = largeTitles
viewController.navigationController?.navigationItem.title = title.capitalized
/* ... */
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
Functions.setupNavBar(largeTitles: false, title: "Library", viewController: self)
}
}
答案 2 :(得分:0)
在应用程序委托中使用此代码,该代码将应用于所有ViewController。您必须根据代码中的要求编辑属性:
chromedriver-helper