我有故事板的設置與類NavigationController: UINavigationController, UIViewControllerTransitioningDelegate
與自定義導航欄安裝擴展導航控制器與CustomNavigationBar:UINavigationBar
類下面的導航控制器的所有視圖控制器是NavigationController添加右按鈕在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)
這出於某種原因沒有顯示在導航菜單中添加了下面的代碼。我哪裏錯了?
你需要添加'自我.navigationItem.setRightBarButton(item,animated:false)'在您的基本視圖控制器中的一部分,因爲每個viewController都有它自己的navigationItem,這就是爲什麼您的自定義按鈕沒有顯示。 –
正如您所見,我在NavigationController中添加了這一點。我是否還需要在所有其他ViewController中添加此項? –
如果你使用了一個baseViewController,並在他的viewDidLoad中添加了這個實現,並且讓你的所有其他viewController繼承了你的baseViewController,那麼你只需要添加一次 –