我在以下代码的帮助下在多个 View Controller 中完成了透明导航栏。我想减少主类文件中的代码行,也尽量避免代码重复。所以,我需要为下面的代码创建子类。请帮助我
// NavigationBar Tranparant
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.view.backgroundColor = .clear
最佳答案
如果您通过 Storyboard创建元素,那么只需创建 UINavigationBar
的子类并将您的属性添加到 awakeFromNib
函数中。
现在在您的 Storyboard中,选择 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)
在您以编程方式创建 View 时使用。 (这就是我们实现的原因,因为我们将以编程方式创建 NavigationController)
required init?(coder: NSCoder)
在从 storyboard/xib 创建 View 时使用。
因为后者是必需的,我们也在这里设置了我们的导航..
关于ios - Swift 为透明导航栏创建子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52025653/