【问题标题】:UINavigationController rightbutton disappearsUINavigationController 右键消失
【发布时间】:2015-02-07 16:11:00
【问题描述】:

我正在尝试将主页按钮添加到导航控制器。因此我创建了下面的类并将我的导航控制器分类。我的按钮出现在我的第一个视图上。当我导航到其他视图(我的图片中的表格视图)时,添加的按钮消失了。我正在使用 segues 推送到另一个视图。

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)

    }
}

在我的 mainViewController 没有导航控制器之前。相反,每个按钮都在推动具有单独导航控制器的新视图控制器,并且我的代码正在运行。如果您能告诉我如何解决此问题,我将不胜感激。

【问题讨论】:

标签: ios swift uinavigationcontroller


【解决方案1】:

您必须在每个控制器中添加按钮,因为按下时每个控制器的导航栏都会更新。因此为什么后退按钮标签会发生变化。

因此,在您想要主页按钮的每个控制器中输入相同的代码。

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

使用情节提要更容易拖动条形按钮项目,然后为其创建一个弹出到根目录的操作。

【讨论】:

  • 谢谢。但是有什么简单的方法可以使用某些类等,这样我就不会一遍又一遍地添加主页按钮。
  • 您可以为您使用的每个控制器类型创建一个子类,其中包含 viewDidLoad 中的代码。然后再次为您的特定控制器类子类。当您调用 [super viewDidLoad] 时,它将添加主页按钮。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-23
    • 1970-01-01
    • 1970-01-01
    • 2011-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多