我在 UINavigationController 中嵌入了几个 View Controller 。我想为每个 viewController 自定义导航栏标题的外观。调用setCustomTitleInNavBar
的最佳方法是什么? .如果在 viewDidLoad 中调用,self 还没有初始化,应用会崩溃。在 ViewWillAppear 中,当 View 显示给用户时,标题尚未显示。如果这不是正确的方法,请建议替代实现。
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)
}
}
最佳答案
这是一种通过协议(protocol)实现它的方法:
// Protocol
protocol NavigationBarSetUpProtocol: class {
// Add more param if needed
func setupNavigationBar(with title: String)
}
// Default implemention
extension NavigationBarSetUpProtocol where Self: UIViewController {
// Default implementation
func setupNavigationBar(with title: String) {
// configure you VC navigation item with : self.navigationItem.titleView = ...
}
}
// VC A
class ViewControllerA: UIViewController, NavigationBarSetUpProtocol {
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationBar(with: "HOME")
}
}
// VC B
class ViewControllerB: UIViewController, NavigationBarSetUpProtocol {
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationBar(with: "PROFILE")
}
}
关于ios - 是调用方法来改变导航栏的外观吗? swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44096221/