Swift 4仅为一个视图控制器设置导航属性

问题描述 投票:0回答:1

我试图只让一个视图控制器的导航栏半透明并改变其他一些属性。

在用户离开这个VC后,我希望它回到'正常',即我在AppDelegate中拥有的东西。

我是否必须重置viewWillDisappear中的每一行?如果是这样,我将用于背景图像/阴影图像作为默认导航栏设置?

    // Make Nav Bar Translucent and Set title font/color
    self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
    self.navigationController?.navigationBar.shadowImage = UIImage()
    self.navigationController?.navigationBar.isTranslucent = true
    self.navigationController?.view.backgroundColor = .clear
    self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 20, weight: .semibold)]
ios swift uinavigationcontroller uinavigationbar
1个回答
0
投票

是的,你必须在ViewWillApear中设置值并重置viewWillDisappear函数中的值,以获得清晰的透明导航栏和普通颜色导航栏。

您可以在UINavigationController上使用扩展,它可以根据某些枚举值设置/重置值。在UIImage上创建扩展,可以从颜色创建图像,以在导航栏和阴影图像上应用为背景图像。

enum NavigationBarMode {
    case normal
    case clear
}

extension UINavigationController {

    func themeNavigationBar(mode: NavigationBarMode) {
        self.navigationBar.isTranslucent = true
        switch mode {
        case .normal:
            let image = UIImage.fromColor(.white)
            navigationBar.setBackgroundImage(image, for: .default)
            navigationBar.shadowImage = UIImage.fromColor(.lightGray)
            navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.black, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 20, weight: .semibold)]
        case .clear:
            let image = UIImage()
            navigationBar.setBackgroundImage(image, for: .default)
            navigationBar.shadowImage = image
            navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 20, weight: .semibold)]
        }
    }
}

extension UIImage {
    static func fromColor(_ color: UIColor) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
        let context = UIGraphicsGetCurrentContext()
        context!.setFillColor(color.cgColor)
        context!.fill(rect)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img!
    }
} 

现在你可以在themeNavigationBar(mode: .transparent)中调用viewWillApear并在themeNavigationBar(mode: .normal)中调用viewWillDisappear来重置。如果您有其他viewControllers的常用导航栏设置,也可以调用themeNavigationbar(mode:.normal)。

您可以使用一些第三方cocoapods

https://github.com/MoZhouqi/KMNavigationBarTransition https://github.com/DanisFabric/RainbowNavigation

© www.soinside.com 2019 - 2024. All rights reserved.