以编程方式创建带有后退按钮的导航控制器

问题描述 投票:2回答:2

我无法在我的AppDelegate中快速解决问题。数周以来,我一直在研究这个小问题(在后台,不是连续进行),并且进行了大量的Google搜索。我一定很想念东西。

[当远程通知进入我的iOS应用时,我想使用一个带有Back按钮的UINavigationController来模态地显示适合该消息的View。这个想法是,当用户处理完通知后,他们可以按“返回”并返回到原来的位置。我无法以编程方式在导航控制器中显示“返回”按钮。

并非我所有现有的视图都嵌入在导航控制器中。因此,我没有在堆栈中找到现有的UINavigationController,而是创建了一个新的UINavigationController并尝试将其设置并呈现如下:

    let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    var mvc = mainStoryboard.instantiateViewControllerWithIdentifier("MyViewIdentifier") as! MySpecialViewController

    /* here is where I setup the necessary variables in the mvc view controller, using data from the remote message.  You don't need to see all that */

    /* this seems to work, I do get what looks to be a navigation controller */
    let newNavController = UINavigationController(rootViewController: mvc)

    /* this part doesn't work, I don't get a "Back" button */
    let btn = UIBarButtonItem(title: "back", style: UIBarButtonItemStyle.Done, target: mvc, action: "backPressed")
    newNavController.navigationItem.leftBarButtonItem = btn

    /* this block seems to work.  The idea is to work through the hierarchy of any modal presentations
    until we get to the screen that is actually showing right now.  I'm not    
    sure this will work in all situations, but it seems to work in my app's hierarchy. */
    var currentViewController = self.window!.rootViewController
    while currentViewController?.presentedViewController != nil {
        currentViewController = currentViewController?.presentedViewController
    }

    /* this I suppose shows my new view controller modally, except without
    the "back" button it's hard to be sure the navigation controller is even there. */
    currentViewController?.presentViewController(newNavController, animated: true, completion: nil)

我确实在相关的视图控制器中有一个称为“ backPressed”的方法。

关于为何不显示导航栏按钮的任何线索?

编辑:我知道backBarButtonItem仅在我们不在堆栈顶部时才会显示。但是,即使我们位于堆栈的顶部,leftBarButtonItem也应该显示出来?

我无法在我的AppDelegate中快速解决问题。数周以来,我一直在研究这个小问题(在后台,不是连续进行),并且进行了大量的Google搜索。我一定是...

ios swift uinavigationcontroller uibarbuttonitem
2个回答
12
投票

这是一个简单的示例,可以从第一个视图中以编程方式设置导航栏:


1
投票

我认为您的视图控制器已被多个使用?

© www.soinside.com 2019 - 2024. All rights reserved.