gpt4 book ai didi

ios - 我的导航 Controller 代码在 swift 中出现问题

转载 作者:行者123 更新时间:2023-11-28 14:12:37 25 4
gpt4 key购买 nike

我现在在我的应用程序中有 5 个 View Controller 用于我的 5 个选项卡栏项目。每个 View Controller 都具有相同的样式,只是标题不同。

这是我在所有这些 View Controller 中单独使用并在 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 as undefined

最佳答案

您可以像这样在 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()
}
}

然后您可以在任何 View Controller 中像这样调用它:

self.setupNavBar(with: false, has: "Check")

我倾向于使用 UIViewController 扩展,因为您实际上是在设置 View Controller 本身的样式,因此可以向其中添加各种其他设置代码。

关于ios - 我的导航 Controller 代码在 swift 中出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52409180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com