Swift 4仅为一个视图控制器

时间:2017-12-16 04:01:44

标签: ios swift uinavigationcontroller uinavigationbar

我试图让一个视图控制器的导航栏保持半透明状态并更改其他一些属性。

用户离开此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)]

1 个答案:

答案 0 :(得分: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)。

您可以使用一些第三方cocoapod

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