Swift为透明导航栏创建子类

时间:2018-08-26 11:10:38

标签: ios swift uinavigationcontroller uinavigationbar

我借助以下代码在多个ViewController中完成了透明导航栏。我想减少主类文件中的代码行,还尝试避免代码重复。因此,我需要为以下代码创建子类。请帮助我

    // NavigationBar Tranparant
    self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
    self.navigationController?.navigationBar.shadowImage = UIImage()
    self.navigationController?.navigationBar.isTranslucent = true
    self.navigationController?.view.backgroundColor = .clear

2 个答案:

答案 0 :(得分:0)

如果要通过情节提要创建元素,则只需创建UINavigationBar的子类,然后在awakeFromNib函数内添加属性即可。

现在,在情节提要中,选择navigationController的navigationBar,然后为它提供刚刚创建的类(来自身份检查器)。

UINavigationBar子类的示例:

import UIKit
class AppBaseNavigationBar : UINavigationBar{
    override func awakeFromNib() {
        super.awakeFromNib()

        self.setBackgroundImage(UIImage(), for: .default)
        self.shadowImage = UIImage()

        self.titleTextAttributes = [
            NSAttributedStringKey.foregroundColor : UIColor.black
        ]
        self.isTranslucent = true 
    }
}

但是,如果您想通过代码(let nav = UINavigationController(navigationBarClass: AppBaseNavigationBar.self, toolbarClass : nil))使用它

您需要添加override init(frame: CGRect)required init?(coder: NSCoder(后者是必需的),因为我们不是来自Nib,并且不会调用awakeFromNib

所以您的子类如下:

import UIKit
class AppBaseNavigationBar : UINavigationBar{


    override init(frame: CGRect) {//for using custom view in code
        super.init(frame: frame)
        setupNavBar()
    }

    required init?(coder aDecoder: NSCoder) {// for using CustomView in IB
        super.init(coder: aDecoder)
        setupNavBar()
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        setupNavBar()

    }

    func setupNavBar(){
        // To avoid duplicate code, move your properties to a function.
        self.setBackgroundImage(UIImage(), for: .default)
        self.shadowImage = UIImage()

        self.titleTextAttributes = [
            NSAttributedStringKey.foregroundColor : UIColor.black
        ]
        self.isTranslucent = true
    }
}
以编程方式创建视图时,使用

override init(frame: CGRect)。 (这就是我们要实现的原因,因为我们将以编程方式创建NavigationController)

从故事板/ xib创建视图时,使用

required init?(coder: NSCoder)

由于需要后者,因此我们也在此处设置了导航。

答案 1 :(得分:0)

创建扩展程序:

extension UIViewController {
    func setTransparentNavBar() {
        self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        self.navigationController?.navigationBar.shadowImage = UIImage()
        self.navigationController?.navigationBar.isTranslucent = true
    }
}

如果要在UIViewController中使用透明导航栏,只需在viewDidLoad中调用setTransparentNavBar。