未添加栏按钮项目

Bar button item is not being added

我遇到了一个问题,我有一个同时具有 navigationControllertabBarControllerviewController。每当在代码中我尝试添加右或左 barButtonItem 或什至向 navigationBar 添加标题时,都没有任何反应。是因为标签栏吗?或者可能是什么问题

viewDidLoad

let addButton = UIBarButtonItem(title: "Add", style: .Plain, target: self, action: #selector(ProfileVC.addNewService))
navigationItem.rightBarButtonItem = addButton

这里是视图控制器在情节提要中的样子

试试这个

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let addButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target: self, action: "buttonMethod")
        navigationItem.leftBarButtonItem = addButton

        navigationController?.navigationBar.barTintColor = UIColor.greenColor()

    }

    func buttonMethod() {
        print("Perform action")
    }

}

正在使用自定义栏按钮试试这个

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

       let btnName = UIButton()
       btnName.setImage(UIImage(named: "imagename"), forState: .Normal)
       btnName.frame = CGRectMake(0, 0, 30, 30)
       btnName.addTarget(self, action: Selector("action"), forControlEvents: .TouchUpInside)

       //.... Set Right/Left Bar Button item
       let rightBarButton = UIBarButtonItem()
       rightBarButton.customView = btnName
       self.navigationItem.rightBarButtonItem = rightBarButton

    }

    func action() {
        print("Perform action")
    }

}

尝试:

parentViewController?.navigationItem.rightBarButtonItem = addButton

因为您的 TabBarController 像这样嵌入到 NavigationController 中:

UINavigationController -> UITabBarcontroller -> YourViewController

你的导航控制器的根viewcontroller是TabbarController 所以您必须创建自定义的 UITabbarController class 然后将您的源代码推送到自定义的 UITabbarController 的 viewDidload 函数中。

树 viewcontroller 将是:NavigationController --> UITabbarController->ViewController

或者您应该为 TabBarController

中的每个 ViewController 设置导航控制器

树 viewcontroller 将是:UITabbarController->NavigationController->ViewController