如何将 UINavigationController 子类附加到它的 UIViewController?
How to attach a UINavigationController subclass to its UIViewController?
我创建了一个 UINavigationController 子class:
class CustomNavigationViewController: UINavigationController {
var imageview:UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationBar.setValue(true, forKey: "hidesShadow")
self.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
self.navigationBar.shadowImage = UIImage()
self.navigationBar.isTranslucent = true
self.view.backgroundColor = UIColor.clear
imageview = UIImageView(frame: CGRect(x: 0, y: -20, width: self.navigationBar.frame.width, height: self.navigationBar.frame.height+20))
imageview.image = UIImage(named: "navbar")
self.navigationBar.addSubview(imageview)
}
}
在我的故事板中,我将 UINavigationController 设置为 CustomNavigationViewController。
在运行,我在navigationBar中的图片正确显示了。
但是,我不知道如何在我的 HomeViewController class 中引用 CustomNavigationViewController。我需要访问它的 imageview 变量。
当 HomeViewcontroller
被推入 CustomNavigationViewController
时,HomeViewController
的 navigationController
属性 已经指向同一个对象。只需将其转换为 CustomNavigationViewController
代码
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let customNavigation = self.navigationController as? CustomNavigationViewController {
// here you got your `customNavigationController`'s object.
customNavigation.imageview // access it
}
}
注意:不要尝试访问 UIViewController
的 navigationController
属性,因为那时它还不会持有导航控制器。
我创建了一个 UINavigationController 子class:
class CustomNavigationViewController: UINavigationController {
var imageview:UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationBar.setValue(true, forKey: "hidesShadow")
self.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
self.navigationBar.shadowImage = UIImage()
self.navigationBar.isTranslucent = true
self.view.backgroundColor = UIColor.clear
imageview = UIImageView(frame: CGRect(x: 0, y: -20, width: self.navigationBar.frame.width, height: self.navigationBar.frame.height+20))
imageview.image = UIImage(named: "navbar")
self.navigationBar.addSubview(imageview)
}
}
在我的故事板中,我将 UINavigationController 设置为 CustomNavigationViewController。
在运行,我在navigationBar中的图片正确显示了。
但是,我不知道如何在我的 HomeViewController class 中引用 CustomNavigationViewController。我需要访问它的 imageview 变量。
HomeViewcontroller
被推入 CustomNavigationViewController
时,HomeViewController
的 navigationController
属性 已经指向同一个对象。只需将其转换为 CustomNavigationViewController
代码
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let customNavigation = self.navigationController as? CustomNavigationViewController {
// here you got your `customNavigationController`'s object.
customNavigation.imageview // access it
}
}
注意:不要尝试访问 UIViewController
的 navigationController
属性,因为那时它还不会持有导航控制器。