我有故事板设置,所有视图控制器扩展导航控制器,类NavigationController: UINavigationController, UIViewControllerTransitioningDelegate
,导航控制器设置自定义导航栏,类CustomNavigationBar:UINavigationBar
这是NavigationController的代码
class NavigationController: UINavigationController, UIViewControllerTransitioningDelegate {
override func viewDidLoad() {
super.viewDidLoad()
}
}
以下是CustomNavigationBar
class CustomNavigationBar: UINavigationBar {
override func awakeFromNib() {
var font = UIFont(name: "Montserrat-Light", size: 17)!
if "ar" == userLocale() {
font = UIFont(name: "DroidSansArabic", size: 17)!
}
let attribtutes = [
NSFontAttributeName: font,
NSForegroundColorAttributeName: UIColor.black,
NSKernAttributeName: 5.0
] as [String : Any]
UINavigationBar.appearance().titleTextAttributes = attribtutes
UINavigationBar.appearance().tintColor = UIColor.black
UINavigationBar.appearance().backgroundColor = UIColor.white
let image = UIImage(named: "back-btn")
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -66), for: .default)
UINavigationBar.appearance().backIndicatorImage = image
}
}
到目前为止,我现在想要添加一个带有自定义视图的右侧栏导航项。我尝试在NavigationController::viewDidLoad()
let customView:UIView = UIView()
customView.backgroundColor = .green
customView.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
let item = UIBarButtonItem(customView: customView)
self.navigationItem.setRightBarButton(item, animated: false)
出于某种原因,这并未显示在导航菜单中。我哪里错了?
答案 0 :(得分:1)
您需要在基本视图控制器中添加自定义导航按钮代码部分,因为每个viewController都有自己的navigationItem
,这就是为什么您的自定义按钮未显示
您需要根据需要使用BaseViewController
类,然后从BaseViewController继承所有viewController,只需在viewDidLoad
像这样
class BaseViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let customView:UIView = UIView()
customView.backgroundColor = .green
customView.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
let item = UIBarButtonItem(customView: customView)
self.navigationItem.setRightBarButton(item, animated: false)
}
}
答案 1 :(得分:0)
你可以使你的NavigationController类符合UINavigationControllerDelegate协议,并在navigationController中修改目标控制器的navigationItem(_ navigationController:UINavigationController,willShow viewController:UIViewController,animated:Bool)方法:
extension RootNavigationController: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
if let viewController = viewController as? YOURCONTROLLER {
viewController.navigationItem.setRightBarButton(YOURITEM, animated: false)
}
}