在Windows中的UIDavigationController上的iOS rightBarButtonItem

时间:2015-06-23 03:32:47

标签: ios swift uibarbuttonitem uinavigationitem

我试图将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_
}

我错过了什么?该按钮不会出现。

4 个答案:

答案 0 :(得分:32)

您应该将menu_button_设置为rightBarButtonItem的{​​{1}}而不是viewController

尝试

navigationController

而不是

self.navigationItem.rightBarButtonItem = menu_button_

答案 1 :(得分:10)

尝试使用以下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

如果您想结清NSString * const kSomeConstantString = @""; // constant pointer ,请查看以下链接中的苹果指南。

https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/BarIcons.html#//apple_ref/doc/uid/TP40006556-CH21-SW1

答案 2 :(得分:2)

创建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()

答案 3 :(得分:1)

在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")
}