2015-02-07 62 views
1

我想将主页按钮添加到导航控制器。因此,我创建了下面的课程和分类我的导航控制器。我的按钮出现在我的第一个视图上。当我导航到其他视图(我的图片中的表格视图)时,添加的按钮消失。我正在使用segues推进另一种观点。UINavigationController右键消失

class ThemedNavigationController: UINavigationController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 


     var home = UIBarButtonItem(image: UIImage(named: "home"), style: UIBarButtonItemStyle.Plain, target: self, action: "doneAction") 
     navigationBar.topItem?.rightBarButtonItem = home 

     navigationBar.barTintColor = anaRenk 
     navigationBar.barStyle = .Black 
     navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: sansSerifName, size: 17)!] 
     UIBarButtonItem.appearance().setTitleTextAttributes(
     [NSFontAttributeName: UIFont(name: sansSerifName, size: 17)!], 
     forState: .Normal) 
    } 

    func doneAction() { // [6] 
     self.navigationController?.popToRootViewControllerAnimated(true) 

    } 
} 

enter image description here

之前我mainViewController没有导航控制器。相反,每个按钮都推动新的viewcontrollers有独立的导航控制器和我的代码正在工作。如果你能告诉我我该如何解决这个问题,我将不胜感激。

+0

这可能帮助:http://stackoverflow.com/questions/6389094/adding-same-button-to-all-view-controllers-in-uinavigationcontroller?rq=1 – Masa 2015-02-07 17:13:14

回答

0

您必须将每个控制器中的按钮添加为每个控制器上的导航栏更新时的按钮。因此为什么后退按钮标签更改。

因此,将相同的代码放在每个你想要一个home按钮的控制器中。

我不会把任何代码放在导航控制器本身。从您想要从家中弹出的第一个控制器开始。

更容易拖动使用故事板中的酒吧按钮项目,然后创建一个动作,它弹出到根。

+0

感谢。然而,是否有任何简单的方法来使用某些类等,以便我不会一遍又一遍地添加该主页按钮。 – Meanteacher 2015-02-07 17:52:52

+0

您可以为每个使用viewDidLoad中的代码的控制器类型创建一个子类。然后再次为您的特定控制器类的子类。当你调用[super viewDidLoad]时,它会添加主页按钮。 – 2015-02-07 18:00:36

0

我想我做到了。它的工作原理,但我不知道它是否是最好的方法。如果您对任何可能的内存泄漏或崩溃问题发表评论,我将不胜感激。谢谢。

class ThemedNavigationController: UINavigationController { 

    required init(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
    } 

    var home:UIBarButtonItem! 
    override func viewDidLoad() { 
     super.viewDidLoad() 

     home = UIBarButtonItem(image: UIImage(named: "home"), style: UIBarButtonItemStyle.Plain, target: self, action: "doneAction") 

     navigationBar.barTintColor = anaRenk 
     navigationBar.barStyle = .Black 
     navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: sansSerifName, size: 17)!] 
     UIBarButtonItem.appearance().setTitleTextAttributes(
     [NSFontAttributeName: UIFont(name: sansSerifName, size: 17)!], 
     forState: .Normal) 
    } 

    override func pushViewController(viewController: UIViewController, animated: Bool) { 

    var exbutton = viewController.navigationItem.rightBarButtonItem? 
    if exbutton == nil { 
     viewController.navigationItem.rightBarButtonItem = home 
    } 
    else { 
     viewController.navigationItem.rightBarButtonItems?.insert(home, atIndex: 0) 

    } 

     super.pushViewController(viewController, animated:animated) 
    } 

    func doneAction() { // [6] 
     popToRootViewControllerAnimated(true) 
    } 
}