直接从导航控制器设置BarButtonItem

时间:2016-06-16 17:03:15

标签: swift swift2

我的导航控制器有一个名为“LoginController”的rootViewController。当我尝试从LoginController的init添加rightBarButtonItem使它工作,但直接在导航控制器中相同的操作不起作用。

这有效:

class LoginController: UIViewController {

    init(){
        super.init(nibName: nil, bundle: nil)

        let button = UIBarButtonItem()
        button.title = "Test2"
        navigationItem.rightBarButtonItem = button        
    }

    ......

}

这不起作用:

class MainNavigationController : UINavigationController{

    private var _distributionProvider : DistributionProvider!

    init(rootViewController: UIViewController, distributionProvider : DistributionProvider) {
        _distributionProvider = distributionProvider
        super.init(rootViewController: rootViewController)

        navigationBar.barTintColor = UIColor(red: 90/255, green: 177/255, blue: 225/255, alpha: 1)

        let button = UIBarButtonItem()
        button.title = "Test"
        navigationItem.rightBarButtonItem = button


    }


   .... 
}

哪里有问题?感谢

1 个答案:

答案 0 :(得分:0)

你必须这样做:

class MainNavigationController: UITabBarController, UITabBarControllerDelegate{
 override func viewDidLoad() {
        super.viewDidLoad()
        delegate = self
    }

    override func viewWillAppear(animated: Bool) {
        let item1 = Item1ViewController()
        let icon1 = UITabBarItem(title: "Title", image: UIImage(named: "someImage.png"), selectedImage: UIImage(named: "otherImage.png"))
        item1.tabBarItem = icon1
        let controllers = [item1]  //array of the root view controllers displayed by the tab bar interface
        self.viewControllers = controllers
    }

    //Delegate methods
    func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool {
        print("Should select viewController: \(viewController.title) ?")
        return true;
    }

}