IOS rightBarButtonItem на UINavigationController в быстром
Я пытаюсь поставить rightBarButtonItem
на второй контроллер представления стека UINavigationViewController
.
Я создаю и устанавливаю кнопку в viewDidLoad
контроллера представления, которую хочу показать. Мой фактический код выглядит следующим образом:
override func viewDidLoad() {
super.viewDidLoad()
menu_button_ = UIBarButtonItem(image: UIImage(named: "menu"),
style: UIBarButtonItemStyle.Plain ,
target: self, action: "OnMenuClicked:")
self.navigationController!.navigationItem.rightBarButtonItem = menu_button_
}
Что мне не хватает? Кнопка не отображается.
Ответы
Ответ 1
Вы должны установить menu_button_
как rightBarButtonItem
вашего viewController
, а не как navigationController
.
Попробуйте
self.navigationItem.rightBarButtonItem = menu_button_
вместо
self.navigationController!.navigationItem.rightBarButtonItem = menu_button_
Ответ 2
попробуйте следующий code.
, он работает для меня.
let homeButton : UIBarButtonItem = UIBarButtonItem(title: "LeftButtonTitle", style: UIBarButtonItemStyle.Plain, target: self, action: "")
let logButton : UIBarButtonItem = UIBarButtonItem(title: "RigthButtonTitle", style: UIBarButtonItemStyle.Plain, target: self, action: "")
self.navigationItem.leftBarButtonItem = homeButton
self.navigationItem.rightBarButtonItem = logButton
И если вы хотите рассчитаться custom image
, пожалуйста, обратитесь к руководству Apple по ссылке ниже.
https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/BarIcons.html#//apple_ref/doc/uid/TP40006556-CH21-SW1
Ответ 3
Создайте расширение UINavigationItem, например -
extension UINavigationItem {
func addSettingButtonOnRight(){
let button = UIButton(type: .custom)
button.setTitle("setting", for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 15.0)
button.layer.cornerRadius = 5
button.backgroundColor = .gray
button.frame = CGRect(x: 0, y: 0, width: 100, height: 25)
button.addTarget(self, action: #selector(gotSettingPage), for: UIControlEvents.touchUpInside)
let barButton = UIBarButtonItem(customView: button)
self.rightBarButtonItem = barButton
}
@objc func gotSettingPage(){
}
}
И вызвать его из viewDidLoad() как -
self.navigationItem.addSettingButtonOnRight()
Ответ 4
В Swift 5
//For righter button item
let rightBtn = UIBarButtonItem(image: UIImage(named: "rightmenu"), style: .plain, target: self, action: #selector(onClickMethod))//Change your function name and image name here
self.navigationItem.rightBarButtonItem = rightBtn
//self.navigationItem.rightBarButtonItem = [rightBtn, anotherBtn] //If you want to add more buttons add like this
//This is your function
@objc func onClickMethod() {
print("Left bar button item")
}