Swift 为透明导航栏创建子类

Swift create subclass for transparent navigation bar

我在下面的代码的帮助下 viewcontroller 完成了多个透明导航栏。我想减少主要 class 文件中的代码行数,同时尽量避免代码重复。所以,我需要为下面的代码创建 subclass 。请帮助我

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

如果您通过故事板创建元素,那么只需创建 UINavigationBar 的子 class 并在 awakeFromNib 函数中添加您的属性。

现在,在您的情节提要中,select 导航控制器的导航栏并将您刚创建的 class(来自身份检查器)赋予它。

UINavigationBar 子示例class:

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

因此您的子class 将如下所示:

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)

当从 storyboard/xib.

创建视图时使用

required init?(coder: NSCoder)

由于后者是必需的,我们也在这里设置了我们的导航..

创建扩展:

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

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