iOS swift 中 UINavigationController 上的 rightBarButtonItem

iOS rightBarButtonItem on UINavigationController in swift

我正在尝试将 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_
}

我错过了什么?按钮没有出现。

您应该将 menu_button_ 设置为 viewControllerrightBarButtonItem 而不是 navigationController

尝试

self.navigationItem.rightBarButtonItem = menu_button_

而不是

self.navigationController!.navigationItem.rightBarButtonItem = menu_button_

尝试以下 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 指南 link。

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

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

在Swift5

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