如何从子视图控制器中更改“后退”按钮文本? [英] How to change Back button text from within the child view controller?

查看:43
本文介绍了如何从子视图控制器中更改“后退”按钮文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道您可以在IB或 prepareForSegue 中设置后退按钮的标题,但是在我的应用程序中,我需要根据可以

I know that you can set the title of the back button from the IB or in prepareForSegue, but in my app I need to update the title according to events that can happen while the controller is visible.

我尝试了但没有任何反应:

I tried but nothing happens:

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 控制器的后退按钮的项目。

例如,如果您有一个带有根viewController A 的导航控制器,并按了viewController B ,则返回按钮那个哟您看到使用 A 配置了 B

The backBarButtonItem is the item used for the back button of the next controller in the navigation stack.
So for example if you have a navigation controller with a root viewController A and you push a viewController B, then the back button title that you see once B is pushed is configured using A.

您可能会遇到这样的情况:

You could have something like this :

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

一次 B 被按下,您会看到带有 Go back to A的后退按钮。

Once B is pushed, you see a back button with "Go back to A".

在您的情况下,棘手的部分是找到<$ c导航堆栈中 B 中的$ c> A 。
可以这样搜索,方法是在 navigationController viewControllers 中进行搜索,如下所示:

In your case the tricky part is to find A in the navigation stack from B. You can do it by searching in the viewControllers of the navigationController like so :

// 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"
}

编辑

在此之后,我不知道有什么 clean 刷新导航栏的方法。

您可以做的是弹出并推送没有动画的视图控制器

I don't know any clean way to refresh the navigation bar after that. Maybe you could ask a separate question just for that.
What you could do is pop and push the view controller without animation

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

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

Or maybe try to create a new UIBarButtonItem instead of changing the title of the existing one.

这篇关于如何从子视图控制器中更改“后退”按钮文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆