ios - 如何从 subview Controller 中更改后退按钮文本?

标签 ios swift cocoa-touch

我知道您可以从 IB 或 prepareForSegue 中设置后退按钮的标题,但在我的应用中,我需要根据 Controller 可见时可能发生的事件更新标题.

我试过了,但没有任何反应:

self.navigationItem.backBarButtonItem = UIBarButtonItem(title: title, style: .Plain, target: nil, action: nil)

这虽然有效,但没有后退箭头:

self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: title, style: .Plain, target: nil, action: "popVC")

有什么想法吗?

最佳答案

backBarButtonItem是用于导航堆栈中next Controller 的后退按钮的项目。
因此,例如,如果您有一个带有 Root View Controller 的导航 Controller A然后你推一个 viewController B ,然后是您看到一次的后退按钮标题 B被推送是使用 A 配置的.

你可以有这样的东西:

A.navigationItem.backBarButtonItem = UIBarButtonItem(title: "Go back to A", style: .Plain, target: nil, action: nil)

一次B按下后,您会看到一个带有“返回 A”的后退按钮。

在您的情况下,棘手的部分是找到 A在来自 B 的导航堆栈中. 您可以通过搜索 viewControllers 来完成的 navigationController像这样:

// This code works from the `B` view controller
let viewControllers = self.navigationController?.viewControllers ?? []
if let indexOfCurrent = viewControllers.indexOf(self) where (indexOfCurrent > viewControllers.startIndex) {
    let indexOfPrevious = indexOfCurrent.advancedBy(-1)
    let previousViewController = viewControllers[indexOfPrevious]
    previousViewController.navigationItem.backBarButtonItem?.title = "New Title"
}

编辑

在那之后我不知道有什么干净的方法来刷新导航栏。也许您可以为此单独提出一个问题。
你可以做的是弹出并推送没有动画的 View Controller

if let navigationController = self.navigationController {
    navigationController.popViewControllerAnimated(false)
    navigationController.pushViewController(self, animated: false)
}

或者尝试创建一个新的 UIBarButtonItem而不是更改现有标题。

关于ios - 如何从 subview Controller 中更改后退按钮文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39065349/

相关文章:

ios - Swift:如何抑制特殊字符的解释并提供字符串文字

iphone - 如何在 iPhone 上测试 Xcode 项目?

ios - appDelegate 实践

ios - 在IDE中呈现ViewController黑屏或线程调试

ios - 重新加载数据未调用 cellForRowAtIndexPath :

ios - iOS Quartz 2D 中的线性化 PDF?

swift - 如何将模块导入到xcode中

ios - 如何检查目录是否存在?

ios - SKProduct localizedTitle 总是英文

ios - 自动调整包含 UICollectionView 的 UITableViewCell