如何从单独的班级访问导航控制器中的标题?我通过Storyboard将mainVC
嵌入到导航控制器中。我可以从viewDidLoad
的同一类中的self.navigationItem.title = "MyTitle"
内部访问标题。但是,我需要像这样从单独的类'CustomNavigation
访问标题:
class: CustomNavigation: UIViewController() {
override func viewDidLoad(){
super.viewDidLoad()
func createCustomNav(){
self.navigationItem.title = "MyTitle"
}
}
}
很遗憾,它不起作用。我也尝试过:
func createCustomNav(){
let nav = UINavigationBar()
let title = UINavigationItem(title: "MyTitle")
nav.setItems([title], animated: false)
self.view.addSubview(nav)
}
这也不起作用。我没有任何错误。
我在mainVC内部实例化CustomNavigation
:var customNavigation = CustomNavigation()
任何帮助将不胜感激!
设置描述您要完成的工作的协议。
protocol NavigationTitler {
func updateTitle(with title: String)
}
定义您的班级将如何使用该协议。
class CustomNavigation: UINavigationController {
var titleDelegate: NavigationTitler?
func work() {
if let del = titleDelegate {
del.updateTitle(with: "Title from other object")
}
}
}
实施协议(适用于您的mainVC
)。
class ViewController: UIViewController, NavigationTitler {
var customNavigation: CustomNavigation?
func updateTitle(with title: String) {
self.navigationItem.title = title
}
func buildCustomController() {
customNavigation = CustomNavigation()
customNavigation!.titleDelegate = self
}
}