簡體   English   中英

UINavigationController 上的 iOS 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_rightBarButtonItem您的viewController而非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請在下面的鏈接中查看蘋果指南。

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

在斯威夫特 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")
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM