如何在iOS 11中撤消透明导航栏?

时间:2018-11-13 01:27:56

标签: swift uinavigationcontroller uinavigationbar

我正在尝试在iOS 11中创建一个透明的NavigationBar。

我将以下代码放入VC中,该代码可以正常工作,但是当将另一个VC推到顶部时,它保持透明。

(我以为再次将backgroundImage设置为nil可以,但是没有用。)

推送新的VC时如何获得白色背景?

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.navigationController?.navigationBar.prefersLargeTitles = false
    self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
    self.navigationController?.navigationBar.shadowImage = UIImage()
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    self.navigationController?.navigationBar.prefersLargeTitles = true
    self.navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
    self.navigationController?.navigationBar.shadowImage = nil
}

1 个答案:

答案 0 :(得分:0)

您可以添加扩展名以简化与 UINavigationBar

的交互
extension UINavigationBar {

    func makeTransparent() {
        self.setBackgroundImage(UIImage(), for: .default)
        self.shadowImage = UIImage()
        self.isTranslucent = true
    }

    func undoTransparency() {
        self.setBackgroundImage(nil, for: .default)
    }

    func makeLargeAndTransparent() {
        makeTransparent()

        self.prefersLargeTitles = true
        self.backgroundColor = .clear
        self.barTintColor = *barTintColor*
        self.tintColor = *tintColor*
        self.largeTitleTextAttributes = [
             .font: *font.of(size: 34)*,
             .foregroundColor: *foregroundColor*
        ]

        self.titleTextAttributes = [
             .font: *font.of(size: 17)*,
             .foregroundColor: *foregroundColor*
        ]
    }

    func makeDefault() {
        undoTransparency()

        self.prefersLargeTitles = false

        self.barTintColor = *barTintColor*
        self.tintColor = *tintColor*
        self.titleTextAttributes = [
            .font: *font.of(size: 17)*,
            .foregroundColor: *foregroundColor*
        ]
    }
}