删除 iOS UIBarButtonItem 的标题文本

我想做的是删除UIBarButtonItem的“Back”按钮中的文本,只在导航栏上留下蓝色的雪佛龙。请记住,我开发的是 iOS 7。我尝试了几种方法,包括但不限于:

这是我不喜欢的图像方法(图像看起来不合适):

UIBarButtonItem *barBtnItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iOS7BackButton"] style:UIBarButtonItemStylePlain target:self action:@selector(goToPrevious:)];
self.navigationItem.leftBarButtonItem = barBtnItem;

我尝试过的另一种方法是这样的,它根本不起作用(没有显示任何东西):

UIBarButtonItem *barBtn = [[UIBarButtonItem alloc]init];
barBtn.title=@"";
self.navigationItem.leftBarButtonItem=barBtn;

我想要实现的是类似iOS 7 Music应用程序中的后退按钮,它只有一个叉形符号。

谢谢。

128943 次浏览

当你设置按钮的标题时,使用@""而不是@""。

——编辑

当你尝试其他字符串时有什么变化吗?我自己成功地使用了以下代码:

UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:backString style:UIBarButtonItemStyleDone target:nil action:nil];
[[self navigationItem] setBackBarButtonItem:backButton];

backString是一个被设置为@" "或@"Back"的变量,这取决于我是在iOS 7还是更低的版本上。

需要注意的一点是,这段代码不在我想为其定制后退按钮的页面的控制器中。它实际上在导航堆栈之前的控制器中。

没有一个答案对我有帮助。但是一个技巧做到了——我只是在按下它之前清除了视图控制器的标题(后退按钮将要去的地方)。

因此,当前一个视图没有标题时,在iOS 7上,返回按钮将只有一个箭头,没有文本。

在推送视图的viewWillAppear上,我放回了原来的标题。

在iOS7上,苹果为UINavigationBar引入了两个新属性,'backIndicatorTransitionMaskImage'和'backIndicatorImage'。

只需调用一次:

[[UINavigationBar appearance] setBackIndicatorImage:[UIImage imageNamed:@"your_image"]];
[[UINavigationBar appearance] setBackIndicatorTransitionMaskImage:[UIImage imageNamed:@"your_image_mask"]];

它将呈现一个自定义图像,而不是默认的雪佛龙字形,继承keyWindow的色调颜色。

至于移除标题,我建议卡马罗斯的答案。记得在推送新视图控制器的视图控制器上调用这个代码。删除一个iOS UIBarButtonItem的标题文本

这适用于我只显示“背面”雪佛龙没有任何文本:

self.navigationController.navigationBar.topItem.title = @"";

在显示导航栏的视图控制器的viewDidLoad中设置此属性,它将完成操作。

注意:我只在iOS 7中测试了它,这在问题的范围内。

在你的第一个ViewController的prepareForSegue:方法中,你设置视图标题为@"",所以当下一个视图被推送时,它将显示前一个ViewController标题为@""。

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
self.navigationItem.title = @" ";
}

唯一的问题是,当你点击返回按钮时,你之前的视图将没有标题,所以你可以在viewWillAppear上再次添加它:

- (void)viewWillAppear:(BOOL)animated{
self.navigationItem.title = @"First View Title";
}

我不太喜欢这个解决方案,但它是可行的,我没有找到其他方法来做到这一点。

如果你正在使用故事板,你可以去到ViewController的Navigation ItemAttributes Inspector(点击Navigation Bar),并将Back Button属性设置为“”(一个空格字符)。这将设置后退按钮标题为一个空格字符,使雪佛龙可见。没有必要乱写代码。

example image

注意,这将设置Back Button标题为Back按钮,它会segue到这个视图控制器,而不是将显示在控制器内部的Back Button !

在iOS7和ios6上,这个问题的简单解决方案是在viewDidLoad中设置自定义标题视图:

- (void)viewDidLoad {


[super viewDidLoad];


UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
titleLabel.text = self.title;
titleLabel.backgroundColor = [UIColor clearColor];


[titleLabel sizeToFit];


self.navigationItem.titleView = titleLabel;
}

然后,在viewWillAppear中:您可以安全地调用

self.navigationController.navigationBar.topItem.title = @" ";

因为你的标题视图是自定义视图,当移回导航堆栈时它不会被覆盖。

[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(-60, -60)
forBarMetrics:UIBarMetricsDefault];

然后可以删除后退按钮项标题。

如果你使用故事板,你可以用空格设置导航属性检查返回按钮。

    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
[UIColor clearColor],UITextAttributeTextColor,
nil];
    

[[UIBarButtonItem appearance] setTitleTextAttributes:attributes
forState:UIControlStateNormal];

我也遇到了同样的问题,我是这样做的。

——编辑

这是一个解决方案,当你真的想删除所有UIBarbuttonItem的标题文本。如果您只想删除后栏按钮项的标题,没有一个简单方便的解决方案。在我的情况下,因为我只有几个UIBarButtonItems,需要显示标题文本,我只是改变了那些特定的按钮的titleTextAttributes。如果你想更具体地使用下面的代码,它只会改变导航栏按钮:

NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
[UIColor clearColor],UITextAttributeTextColor,
nil];
    

[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTitleTextAttributes:attributes
forState:UIControlStateNormal];
< p >——编辑 为迅速< / p >
let BarButtonItemAppearance = UIBarButtonItem.appearance()
BarButtonItemAppearance.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.clear], for: .normal)
BarButtonItemAppearance.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.clear], for: .highlighted)
BarButtonItemAppearance.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.clear], for: .selected)

我没有得到很多成功的答案,但我确实找到了一个非常简单的工作。在你的故事板中,你可以点击你的UIViewController的导航项并设置返回按钮文本。我把它设置为一个单独的“”空间,它给了我我正在寻找的行为。enter image description here

设置视图控制器的后退按钮标题而不改变它的标题用法:

objective - c:

self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:self.navigationItem.backBarButtonItem.style target:nil action:nil];

迅速:

navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)

需要明确的是,这是在视图控制器上完成的,如果你点击后退按钮,你会看到。即不是看到'<Settings'你只需要看到'<'然后在你的SettingsViewController上,你可以把这个放在init中。这样你就不会遇到标题不显示的问题当你看视图控制器本身时。

你也可以用这个:

UIBarButtonItem *temporaryBarButtonItem = [[UIBarButtonItem alloc] init];
temporaryBarButtonItem.title = @"";
self.navigationItem.backBarButtonItem = temporaryBarButtonItem;


[temporaryBarButtonItem release];

这对我很有用

我不能让它工作使用Guto Araujo的navigationBar.topItem.title = @"";的答案

然而,我可以通过在视图控制器的init方法中设置self.title = @""来获得预期的效果。(在__ABC1中设置它很重要,viewDidLoad将不起作用。)

其实你只需要一个技巧就可以做到:

重写UINavigationBar类并添加以下代码行:

- (void)layoutSubviews{
self.backItem.title = @"";
[super layoutSubviews];
}

然后用这个自定义UINavigationBar类初始化你的UINavigationController ..等等。UINavigationController * navController = [[UINavigationController alloc] initWithNavigationBarClass:[CBCNavigationBar class] toolbarClass:nil];

希望这能有所帮助

只需设置UIBarButtonItem外观的偏移量。

[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(-1000, -1000)
forBarMetrics:UIBarMetricsDefault];

这在iOS 7+中很管用:

在viewDidLoad:

self.navigationItem.backBarButtonItem.title = @" ";

是的,引号之间有空格。

我用唐纳莉亚的答案拼凑出了一些东西。这是解决方案如何出现在我的UIViewController子类:

var backItemTitle:String?


override func viewDidLoad() {
super.viewDidLoad()


//store the original title
backItemTitle = self.navigationController?.navigationBar.topItem?.title


//remove the title for the back button
navigationController?.navigationBar.topItem?.title = ""
}


override func willMoveToParentViewController(parent: UIViewController?) {
super.willMoveToParentViewController(parent)
if parent == nil {


//restore the orignal title
navigationController?.navigationBar.backItem?.title = backItemTitle
}
}

原始答案的问题是,当您弹出回控制器时,它会从控制器中删除标题。尝试在viewWillDisappear中重置标题在转换过程中为时已晚;它会导致标题反弹,而不是很好地呈现动画。然而,willMoveToParentViewController发生得更快,并允许正确的行为。

注意:我只测试了一个普通的UINavigationController push / pop。在其他情况下可能会出现其他意想不到的行为。

这是使用子类navigationController删除“Back”。

我要用这个来删除它,通过应用程序永久删除。

//.h
@interface OPCustomNavigationController : UINavigationController


@end


//.m
@implementation OPCustomNavigationController


- (void)awakeFromNib
{
[self backButtonUIOverride:YES];
}


- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
[self backButtonUIOverride:NO];


[super pushViewController:viewController animated:animated];
}


- (void)backButtonUIOverride:(BOOL)isRoot
{
if (!self.viewControllers.count)
return;


UIViewController *viewController;


if (isRoot)
{
viewController = self.viewControllers.firstObject;
}
else
{
int previousIndex = self.viewControllers.count - 1;


viewController = [self.viewControllers objectAtIndex:previousIndex];
}


viewController.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@""
style:UIBarButtonItemStylePlain
target:nil
action:nil];
}


@end
self.navigationController.navigationBar.topItem.title = @"";
case : <Back as <


override func viewWillAppear(animated: Bool) {
navigationController!.navigationBar.topItem!.title = ""
}
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefaultPrompt];
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(10.0, NSIntegerMin) forBarMetrics:UIBarMetricsDefault];
[[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],
NSFontAttributeName:[UIFont systemFontOfSize:1]}
forState:UIControlStateNormal];

隐藏导航栏的后退按钮标题

UIBarButtonItem *barButton = [[UIBarButtonItem alloc] init];
barButton.title = @""; // blank or any other title
self.navigationController.navigationBar.topItem.backBarButtonItem = barButton;

全球完美解决方案

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {


UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.clearColor()], forState: UIControlState.Normal)
UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.clearColor()], forState: UIControlState.Highlighted)


return true
}

我列出了目前为止对我有效的解决方案。

override func viewDidLoad() {
super.viewDidLoad()






self.navigationController?.navigationBar.topItem?.title = "" // 1


let barAppearace = UIBarButtonItem.appearance()
barAppearace.setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -60), forBarMetrics:UIBarMetrics.Default)  // 2


UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.clearColor()], forState: UIControlState.Normal) //3


UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.clearColor()], forState: UIControlState.Highlighted) //4






}

我为UINavigationController创建了一个自定义类,并将其应用于应用程序中的所有导航控制器。在这个自定义UINavigationController类中,一旦视图加载,我将UINavigationBar委托设置为self

- (void)viewDidLoad {
self.navigationBar.delegate = self;
}

然后我实现委托方法:

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPushItem:(UINavigationItem *)item {


// This will clear the title of the previous view controller
// so the back button is always just a back chevron without a title
if (self.viewControllers.count > 1) {
UIViewController *previousViewController = [self.viewControllers objectAtIndex:(self.viewControllers.count - 2)];
previousViewController.title = @"";
}
return YES;
}

通过这种方式,我简单地将我的自定义类分配给我所有的导航控制器,它清除了所有后退按钮的标题。为了清晰起见,我总是在viewWillAppear中为所有其他视图控制器设置标题,以便标题总是在视图出现之前更新(以防它被这样的技巧删除)。

enter image description here

有时候把事情放在背景中看是有帮助的。这是一个隐藏“返回”文本但仍然显示箭头的最小项目。

故事板

enter image description here

有一个show segue从show Second View Controller按钮到第二个视图控制器。

我还为第二个视图控制器添加了一个导航项,这样它就有了一个标题。这是可选的。它不影响返回按钮。

代码

FirstViewController.swift

import UIKit
class FirstViewController: UIViewController {


@IBAction func showSecondViewControllerButtonTapped(sender: UIButton) {


// hide the back button text
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
}
}

SecondViewController.swift

import UIKit
class SecondViewController: UIViewController {
// Nothing at all needed here
}

替代方法(仅IB,无代码)

在故事板上选择第一个视图控制器的导航项(不是第二个)。只需为Back Button文本输入一个空格。

enter image description here

这是我正在做的,这是更简单的删除后退按钮的标题

override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar?.backItem?.title = ""
}

只要为后退按钮导航项输入一个空间就可以了!!

这在iOS10系统中很管用。从视图控制器的viewDidLoad调用这个。

self.navigationController?.navigationBar.topItem?.title = ""

斯威夫特3

navigationController?.navigationBar.topItem?.title = ""

如果你像我一样使用自定义视图而不是UINavigationBar,并且你被后退按钮困住了,那么你必须做一些感觉有点笨拙的工作。

[self.navigationController.navigationBar setHidden:NO];
self.navigationController.navigationBar.topItem.title = @"";
[self.navigationController.navigationBar setHidden:YES];

似乎如果它没有被呈现,那么无论如何它都会尝试显示一个标题,这意味着它会被显示,然后在它被绘制之前隐藏,这解决了问题。

只需要在ParentViewController中设置空白标题文本。

self.navigationItem.title=@"";

如果你需要标题文本,那么在ParentViewController中放入下面两个方法。

-(void)viewWillAppear:(BOOL)animated
{
self.navigationItem.title = @"TitleText";
}


-(void)viewWillDisappear:(BOOL)animated
{
self.navigationItem.title=@"";
}
extension UIViewController{
func hideBackButton(){
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
}
}

实现你自己的UIViewController基类并覆盖setTitle:

@interface CustomViewController : UIViewController
@end


@implementation CustomViewController


- (void)setTitle:(NSString *)title {
super.title = @""; // This will remove the "Back" title
UILabel *titleView = [UILabel new];
// customize the label as you wish
titleView.text = title;
[titleView sizeToFit];
self.navigationItem.titleView = titleView;
}


@end

现在,在任何你想要设置标题的UIViewController中,你可以像往常一样只写self.title = @"MyTitle",当推入一个新的UIViewController时,后栏项上不会出现文本。

我已经做了一个非常简单的零配置类别来隐藏所有的后退按钮标题通过应用程序,你可以检查在这里。这个问题已经有了公认的答案,但对其他人来说,它可能是有帮助的。

编辑:

. h文件

#import <UIKit/UIKit.h>


@interface UINavigationController (HideBackTitle)
extern void PJSwizzleMethod(Class cls, SEL originalSelector, SEL swizzledSelector);


@end

m文件

#import "UINavigationController+HideBackTitle.h"
#import <objc/runtime.h>




@implementation UINavigationController (HideBackTitle)


+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
PJSwizzleMethod([self class],
@selector(pushViewController:animated:),
@selector(pj_pushViewController:animated:));
});
}


- (void)pj_pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
UIViewController *disappearingViewController =  self.viewControllers.lastObject;
if (disappearingViewController) {
disappearingViewController.navigationItem.backBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}
if (!disappearingViewController) {
return [self pj_pushViewController:viewController animated:animated];
}
return [self pj_pushViewController:viewController animated:animated];
}






@end


void PJSwizzleMethod(Class cls, SEL originalSelector, SEL swizzledSelector)
{
Method originalMethod = class_getInstanceMethod(cls, originalSelector);
Method swizzledMethod = class_getInstanceMethod(cls, swizzledSelector);


BOOL didAddMethod =
class_addMethod(cls,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));


if (didAddMethod) {
class_replaceMethod(cls,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}

在iOS 11中,你可以使用下面的代码来隐藏返回按钮的标题:

迅速:

UIBarButtonItem.appearance().setTitleTextAttributes([ NSForegroundColorAttributeName : UIColor.clear ], for: .normal)
UIBarButtonItem.appearance().setTitleTextAttributes([ NSForegroundColorAttributeName : UIColor.clear ], for: .highlighted)

这段代码并没有从导航栏中移除标题,只是使其透明,返回按钮仍然保留标题的空间。如果你需要为视图控制器标题提供更多空间,那么你需要使用另一种解决方案。

< >强劲迅速3.1 你可以通过实现UINavigationController的委托方法来做到这一点。它将只隐藏带有返回按钮的Title,我们仍然会得到返回箭头图像和默认功能

func navigationController(_ navigationController: UINavigationController,
willShow viewController: UIViewController, animated: Bool) {
let item = UIBarButtonItem(title: " ", style: .plain, target: nil,
action: nil)
viewController.navigationItem.backBarButtonItem = item
}

这是更好的解决方案。

其他的解决方案是危险的,因为它是黑客。

extension UINavigationController {


func pushViewControllerWithoutBackButtonTitle(_ viewController: UIViewController, animated: Bool = true) {
viewControllers.last?.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
pushViewController(viewController, animated: animated)
}
}

如果你想在iOS11中删除后退按钮项目标题,你可以试试!

@implementation UIView (PrivateBackButton)
    

+ (void)initialize {
if ([NSProcessInfo processInfo].operatingSystemVersion.majorVersion < 11.0) return;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[NSObject hookInstanceMethodForClass:[self class] originalMethod:@selector(layoutSubviews) newMethod:@selector(mc_layoutSubviews)];
});
}
    

- (void)mc_layoutSubviews {
[self mc_layoutSubviews];
[self updateiOS11LaterUI];
}
    

- (void)updateiOS11LaterUI {
if ([NSProcessInfo processInfo].operatingSystemVersion.majorVersion < 11.0) return;
if (![self isKindOfClass:NSClassFromString(@"_UIBackButtonContainerView")]) return;
        

[self removeAllSubviews];
[self.superview mas_remakeConstraints:^(MASConstraintMaker *make) {
make.width.mas_equalTo(@44);
}];
}
    

@end

2021年更新:使用NXNavigationExtension