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

标签 ios swift function uinavigationcontroller uinavigationbar

我现在在我的应用程序中有 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/

相关文章:

ios - iOS7 中的 MFMailComposeViewController 自定义

android - Android 和 iOS 的 Paypal 集成,可能吗?

ios - 使用 UIGraphicsPDFRenderer 创建 PDF 时添加像 "page x of y"这样的页脚

SQL函数来计算字符串在列中出现的次数?

objective-c - 如何本地化 iOS Storyboard

ios - 试图理解#selector 及其方法所发生的事情需要参数 Swift 3

swift - 没有颜色的淡入淡出过渡?

ios - 开始和结束标签不匹配 - Xcode Storyboard 错误

React : why isn't my function returning multiple divs? 中的 Javascript 函数

javascript - 变量未写入数组 - Javascript