【发布时间】:2017-05-21 11:16:52
【问题描述】:
我在 UINavigationController 中嵌入了几个视图控制器。我想为每个 viewController 自定义导航栏标题的外观。致电setCustomTitleInNavBar 的最佳方法是什么?如果在 viewDidLoad 中调用,self 还没有初始化,应用会崩溃。在 ViewWillAppear 中,当视图显示给用户时,标题尚未显示。如果这不是正确的方法,请建议替代实施。
class CustomMethods {
func setCustomTitleInNavBar(textValue:String, VC:UIViewController) -> UIView {
let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
titleLabel.text = textValue
titleLabel.adjustsFontSizeToFitWidth = true
titleLabel.textAlignment = NSTextAlignment.center
VC.navigationItem.titleView = titleLabel
return VC.navigationItem.titleView!
}
}
//call method on the current view controller to modify the nav bar title
class someViewController: UIViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
setCustomTitleInNavBar(textValue: "Where to come?", VC: self)
}
}
【问题讨论】:
-
使用有助于设置
navBar标题的方法创建协议。在每个 VC 中实现协议并调用viewDidLoad中的方法。您可以向此方法添加默认实现以设置默认标题。
标签: ios swift3 uinavigationbar