199

What I wanted to do is to remove the text from the 'Back' button of a UIBarButtonItem, leaving only the blue chevron on the navigation bar. Keep in mind that I'm developing for iOS 7. I've tried several methods, including, but not limited to:

This is the image method which I did not like (the image looked out of place):

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

Another method I tried was this, which simply did not work (nothing was displayed):

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

What I wanted to achieve is something like the back buttons found in the iOS 7 Music app, which only featured a single chevron.

Thanks.

TheNeil
  • 3,321
  • 2
  • 27
  • 52
Pan Ziyue
  • 2,287
  • 2
  • 16
  • 17
  • look at this answer http://stackoverflow.com/a/20300577/1589731 – ayalcinkaya Jul 03 '14 at 16:26
  • Why don't you take image of what is your requirement? And refer it in leftBarButtonItem. – Vishal Sharma Sep 18 '15 at 08:19
  • The reason why I didn't use the picture method is 1. It's very hard to get a perfect picture of the back button and 2. There will be some form of misalignment with the image and it doesn't look natural, and that's why I took to StackOverflow for help on how to accomplish this natively. – Pan Ziyue Sep 18 '15 at 08:25

39 Answers39

412

To set the back button title for a view controller without changing its title use:

Objective-C:

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

Swift:

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

To be clear, this is done on the view controller that you would see if you hit the back button. i.e. instead of seeing '< Settings' you want to just see '<' then on your SettingsViewController you would put this in your init. Then you don't get any of the problems of the title not showing when you're looking at the view controller itself.

shim
  • 9,289
  • 12
  • 69
  • 108
DonnaLea
  • 8,643
  • 4
  • 32
  • 32
  • 1
    I don´t know why the other answer is marked as correct, its just removing the title so the back button doent has a "title" to show, but thats not the correct approach at all! This one should be the right answer. – Pach May 15 '14 at 11:13
  • @Pach thanks. Admittedly I only just posted my answer (8 months after it was asked). I'm glad this was helpful for you though. – DonnaLea May 15 '14 at 17:15
  • This won't work if the main title of the navigation item in the main view controller that you are navigating *away* from changes dynamically. – Dalmazio May 19 '14 at 04:59
  • Can I set this globally for ALL back bar buttons? – rebellion May 20 '14 at 21:39
  • @rebellion not that I'm aware of, but I haven't searched to be able to do that either. Alternatively, you could have a base class UIViewController which does this automatically for all your View Controllers that subclass it – DonnaLea May 20 '14 at 22:23
  • 1
    This works great, but it still has a very large width if I have extra UIBarButtonItems. Also, the width property doesn't work, probably because it's a "radio button", whatever that means (in the docs). Is there a way to set the width to only the needed width? Thanks! – Zoyt Jun 30 '14 at 20:31
  • 8
    Also to anyone using Swift, it's navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style: .Plain, target: nil, action: nil). Not hard to convert from Obj-C to Swift, but I'll save you the troublef – Zoyt Jun 30 '14 at 20:32
  • 15
    @BenjaminPiette are you calling this on the UIViewController that you would see if you hit the back button? Not the UIViewController that displays the back button. – DonnaLea Oct 22 '14 at 16:07
  • @DonnaLea oh no i didn't. I'll try that again, thanks for letting me know! – Benjamin Piette Oct 22 '14 at 20:21
  • 1
    @DiscDev I'm using this in production, for iOS 7 and 8 without a problem. Do you have the code in the previous UIViewController? The one you'd see if you hit back? – DonnaLea Jan 08 '15 at 16:46
  • @DonnaLea yes - it's in the "previous" controller. I tried it in 3-4 different places and it works in some cases, but not in others. – DiscDev Jan 08 '15 at 17:06
  • 1
    @DiscDev in the view controllers that aren't working, are you sure the code is being called? Possibly you have it in an init which isn't being called? Keep in mind that initWithCoder is called for UIViewControllers that are created with storyboard, but initWithNibName:bundle: is called when instantiating with an XIB. – DonnaLea Jan 08 '15 at 17:13
  • @DonnaLea it's in viewDidLoad in each VC. I don't use storyboards. Breakpoints confirmed code is called. – DiscDev Jan 08 '15 at 20:52
  • 1
    @DiscDev maybe try moving that logic into an init method that gets called since this code has nothing to do with the view being loaded, it doesn't really belong in viewDidLoad. Just thought, but it is weird it doesn't work for you in viewDidLoad. – DonnaLea Jan 11 '15 at 03:52
  • @Zoyt thanks for the Swift version, I've added it to the answer for easier reference for people. – DonnaLea Apr 23 '15 at 08:23
  • It's strange that `[self.navigationItem.backBarButtonItem setTitle:@"go back"];` doesn't work. You have do create a new bar button item. – Steve Moser Aug 18 '15 at 17:42
  • 2
    What an elegant solution! Thanks. It just didn't feel right to do the offset thing. – Hyder Oct 07 '15 at 06:34
  • I originally put this in viewWillAppear but discovered that sometimes that method is not called while moving through the navigation. I've not been able to determine why that is, but just moved the line of code to viewDidLoad in those cases. – Fran K. Mar 11 '16 at 16:58
  • Instead of putting this code in the view controller, you should subclass the UINavigationController and use the "willShowViewController" delegate method to put this line of code. This will affect all your navigation in your app with a navigation controller subclassed. Tell me if you're interested in the code so I will reply to this thread. – Tom Jun 21 '16 at 06:31
  • this works perfectly without messing with the title alignement – elbuild Jun 21 '16 at 16:17
  • 2
    this solution works perfect if you write this line of code on previous controller in navigation stack. – Bohdan Savych Feb 24 '17 at 10:12
198
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(-60, -60)
                                                         forBarMetrics:UIBarMetricsDefault];

Then you can remove the back button item title.

If you use Storyboard, you can set navigation attributes inspector Back Button with space.

Or Arbel
  • 2,965
  • 2
  • 30
  • 40
andyleehao
  • 2,412
  • 1
  • 15
  • 8
  • 1
    This is an interesting solution to this problem. I don't have the luxury of counting on the pushing VC to change its title, so setting the appearance for all UIBarButtonItem back button titles is pretty genius! – Mr. T Feb 19 '14 at 23:27
  • 96
    There is a problem with large titles: they are not centered but pushed to the right, like if the back button text was still there – sonxurxo Jul 15 '14 at 15:10
  • Looks much better than the selected answer, if you need to restore the original setting when your VC is closed. – diegoreymendez Oct 29 '14 at 15:50
  • 11
    This doesn't work if the user has turned on "Accessibility - Button shapes" – Mikael Bartlett Nov 21 '14 at 08:40
  • Can you explain "you can set navigation attributes inspector Back Button with space." I didn't find this in story boarf – Mihir Mehta Feb 04 '15 at 12:14
  • In the back button, enter empty space. – andyleehao Feb 06 '15 at 03:30
  • 22
    I think this is a better answer : `[[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState:UIControlStateNormal];` – benjamin Jul 29 '15 at 14:52
  • 1
    Make sure to call `UIBarMetricsCompact` as well if you want it to work when rotated on the iPhone. – thattyson Jul 29 '15 at 16:51
  • 19
    Any solution with magic numbers in it is a bad idea. With the push to autolayout, size classes, accessibility features, etc.. using constant values like this is bound to bite you. – Michael Peterson Mar 17 '16 at 21:15
  • 3
    To improve upon benjamin's comment, you should set this for `UIControlStateHighlighted` as well – n_b Mar 24 '16 at 19:54
  • 1
    Benjamin's answer might work, but it will also set any bar button item to a clear text. – kevinl Dec 01 '16 at 18:18
  • This causes the text to animate when the push transition is not animated. – Cezar Signori Jul 12 '17 at 13:38
  • 2
    I would like to se face people who used it and now comes iOS 11 :D – Michal Zaborowski Jul 13 '17 at 10:13
  • 2
    Be careful if use this in iOS 11! It causes `UIViewAlertForUnsatisfiableConstraints` and you can lose a lot of time scratching your head to find the source of the issue. – Paul Razvan Berg Aug 21 '17 at 12:43
  • If in other navigation items you'd like to put a title on the left button, it would also disappear. – Avi Sep 07 '17 at 08:15
  • In iOS 11 just sent the horizontal value and not the vertical and it seems to work ok, minus the broken constraint. – Iain Smith Oct 04 '17 at 14:42
  • Anyone trying to hide back button title throughout the all viewcontrollers in app you may want to check [my answer below](https://stackoverflow.com/a/46153030/3308174), which has no side effects and hides only the back button title – Pratik Jamariya Nov 06 '17 at 08:01
127

If you are using Storyboards you can go to Attributes Inspector of the ViewController's Navigation Item (click on Navigation Bar) and set the Back Button property to " " (one space character). This will set the Back Button title to one space character, leaving the chevron visible. No need to mess with code.

example image

Note that this will set Back Button title for the Back Button that will segue to this View Controller from the one that was pushed on top of it, not for the Back Button that will be displayed inside this Controller!

Nikita Kukushkin
  • 14,648
  • 4
  • 37
  • 45
  • 10
    I wish I could upvote this more: "Note that this will set Back Button title for the Back Button that will segue to this View Controller form the one that was pushed on top of it, not for the Back Button that will be displayed inside this Controller!" – Jayson Lane Sep 03 '14 at 19:33
120

This works for me to display just the 'back' chevron without any text:

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

Set this property in viewDidLoad of the View Controller presenting the navigation bar and it will do the trick.

Note: I have only tested it in iOS 7, which is within scope of the question.

Guto Araujo
  • 3,824
  • 2
  • 21
  • 26
  • 33
    That has a side effect of removing the title label in the middle of the navigation bar. – Pwner Dec 02 '13 at 22:45
  • 7
    Set the title of the pushing VC on 'viewWillAppear' with the same property. This way it is not removed. – Guto Araujo Dec 03 '13 at 00:41
  • Well there's a problem. If I set my title in the ```-viewWillAppear``` and your line in ```-viewDidLoad``` in the presenting view controller your method would simply not work and the Back button will still be there. – Pan Ziyue Jan 31 '14 at 14:50
  • @PanZiyue If you set the line above in `viewDidLoad` of the VC you want the chevron without any text, it works. You'd set the title property in `viewWillAppear` of the VC that pushed it. – Guto Araujo Feb 01 '14 at 02:23
  • 5
    I moved that piece of code to ```-viewDidLoad``` of the VC that I do not want the Back text. However, what I found out later on was that when I pop the 2nd VC from the ```navigationController``` the Title text appears shortly after, not immediately. I guess a video would illustrate this better so here it is: [link](https://statixind.net/downloads/personal/stkovrf.mov) – Pan Ziyue Feb 01 '14 at 05:11
  • @PanZiyue Thanks for video. Yes, that's the behavior when you pop the VC without the back title. It seems that because the title was removed from the VC it isn't part of the animation when it moves back in. So it is displayed only when the VC is displayed again when the animation ends. – Guto Araujo Feb 02 '14 at 10:33
  • Well that is problematic. Any way to rectify? – Pan Ziyue Feb 02 '14 at 15:52
  • @PanZiyue It is the way this method works from what I could test. – Guto Araujo Feb 02 '14 at 16:39
  • Put it in my detailsView and it removed the text from another view I have too -- but I don't care I was gonna manually add it myself later anyway....cheers – Mou某 Mar 25 '14 at 09:03
  • 1
    This is not the best answer, please refer to andyleehao's answer:[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault]; – lmnbeyond Jul 08 '14 at 10:38
  • 1
    This is the correct answer as per Apple's documentation: "When the receiver is on the navigation item stack and is second from the top—in other words, its view controller manages the views that the user would navigate back to—the value in this property is used for the back button on the top-most navigation bar. If the value of this property is nil, the system uses the string “Back” as the text of the back button." – Raphael Oliveira May 03 '16 at 07:21
28

enter image description here

Sometimes it is helpful to see things in context. Here is a minimal project that hides the "back" text but still shows the arrow.

Storyboard

enter image description here

There is a show segue from the "Show Second View Controller" button to the second view controller.

I also added a Navigation Item to the second view controller so that it would have a title. This is optional. It does not affect the back button.

Code

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
}

Alternate method (IB only, no code)

On the storyboard select the navigation item for the first view controller (not the second). Just enter a space for the Back Button text.

enter image description here

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
  • Key concept that " for the first view controller (not the second)" as is the name of the VC that you want to come back so it's responsibility to give this title. – BuguiBu Oct 23 '17 at 15:31
27

When you're setting the button's title, use @" " instead of @"".

--EDIT--

Does anything change when you try other strings? I'm using the following code myself successfully:

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

backString is a variable that is set to @" " or @"Back", depending on if I'm on iOS 7 or a lower version.

One thing to note is that this code isn't in the controller for the page I want to customize the back button for. It's actually in the controller before it on the navigation stack.

Kamaros
  • 4,536
  • 1
  • 24
  • 39
  • Hmm, iOS 7 doesn't seem to change that. It keeps using "Back" as the title. If I put `setLeftBarButtonItem:backButton` instead nothing would be there. – Pan Ziyue Sep 30 '13 at 16:07
  • 1
    If that's the case, and nothing happens when you set the title to something else, I think you'll have to try moving your code to the parent view controller. I'm using the code I posted above in my prepareForSegue method. – Kamaros Sep 30 '13 at 16:30
15
self.navigationController.navigationBar.topItem.title = @"";
Claudio Castro
  • 1,541
  • 12
  • 28
  • 1
    You can use backItem instead of topItem. TopItem will hide the title , while backItem will hide the back button title. – Ravi Ojha Nov 13 '15 at 06:31
  • 2
    This is the only solution if the childViewController is at depth 2+ in the NavigationController's children stack – Nathaniel Feb 24 '16 at 19:11
  • 2
    This will also remove the title of the previous view controller. In most cases, this is gonna suck – CalZone Apr 25 '16 at 19:43
11

On iOS7, Apple introduced two new properties to UINavigationBar, 'backIndicatorTransitionMaskImage' and 'backIndicatorImage'.

By simply calling once:

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

It will render a custom image instead of the default chevron glyph, inheriting the keyWindow's tint color.

And for removing the title, I'll suggest Kamaros's answer. Remember to call this code on the view controller that's pushing your new view controller. Removing the title text of an iOS UIBarButtonItem

Community
  • 1
  • 1
DZenBot
  • 4,806
  • 2
  • 25
  • 27
10

I didn't have a lot of success with the provided answers but I did find a really simple work around. In your storyboard, you can click on your UIViewController's Navigation Item and set the back button text. I set it to a single ' ' space and it gave me the behavior I was looking for.enter image description here

Grahambo
  • 467
  • 5
  • 11
10

This worked for me in iOS10. Call this from viewDidLoad of the view controller.

self.navigationController?.navigationBar.topItem?.title = ""
Thomas Kekeisen
  • 4,355
  • 4
  • 35
  • 54
Ravi
  • 119
  • 1
  • 4
6

Simple solution to this problem, working on iOS7 as well as 6, is to set custom title view in 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;
}

Then, in viewWillAppear: you can safely call

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

Because your title view is custom view, it won't get overwritten when moving back in the navigation stack.

Matthes
  • 515
  • 5
  • 12
  • I only needed the latter part of the code and not the blank UILabel. I was calling `[self.navigationItem.backBarButtonItem setTitle:@" "];` in viewWillAppear but it wasn't working on views presented after dismissing a modal view. – Diziet Jan 21 '14 at 13:04
6

Actually you can do this with just one trick:

Override UINavigationBar class and add this line of code:

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

Then initialize your UINavigationController with this custom UINavigationBar class.. etc. UINavigationController * navController = [[UINavigationController alloc] initWithNavigationBarClass:[CBCNavigationBar class] toolbarClass:nil];

Hope this helps

chancyWu
  • 14,073
  • 11
  • 62
  • 81
rordulu
  • 412
  • 4
  • 12
  • This worked for me. Although it seems as if there is a slight stutter in the push animation on iOS 7: the title seems to make room for the back button then centers since there is none. – zekel Aug 07 '14 at 19:40
  • Yeah, try using custom titleView instead of setting the navigationItem.title directly. I think that should fix your problem. – rordulu Aug 27 '14 at 16:11
  • this solution is awesome cause it's globally for every navigationBar which has the sub-class. Thanks – Yetispapa Jun 07 '17 at 08:14
5

I was able to cobble something together using DonnaLea's answer. This is how the solution appears in my UIViewController subclass:

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

The problem with the original answer is that it removes the title from the controller when you pop back to it. Attempting to reset the title in viewWillDisappear is too late in the transition process; It causes the title to snap back in instead of animating nicely. However the willMoveToParentViewController happens sooner and allows for the correct behavior.

Caveat: I've only tested this with a normal UINavigationController push / pop. There might be additional unexpected behavior in other situations.

BradB
  • 509
  • 5
  • 15
4

In the prepareForSegue: method of your first ViewController you set that views title to @"", so when the next view is pushed it will display the previous ViewController title which will be @"".

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

The only problem with this is that when you hit the back button your previous view won't have a title, so you may add it again on viewWillAppear:

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

I don't like very much this solution but it works and i didn't find other way to do it.

shim
  • 9,289
  • 12
  • 69
  • 108
Alejandro Figueroa
  • 419
  • 1
  • 4
  • 14
4

SWIFT 3

navigationController?.navigationBar.topItem?.title = ""
Thomas Kekeisen
  • 4,355
  • 4
  • 35
  • 54
Jiří Zahálka
  • 8,070
  • 2
  • 21
  • 17
3

Non of the answers helped me. But a trick did - I just cleared the title of the view controller that pushed (where the back button is going to) just before pushing it.

So when the previous view doesn't have a title, on iOS 7 the back button will only have an arrow, without text.

On viewWillAppear of the pushing view, I placed back the original title.

Kof
  • 23,893
  • 9
  • 56
  • 81
  • 1
    Hmm, this trick works. However it looks like the words up there will flicker sometimes. Not a very good workaround but nevertheless a good one. +1 – Pan Ziyue Oct 17 '13 at 15:27
3
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                [UIColor clearColor],UITextAttributeTextColor,
                                nil];
    
    [[UIBarButtonItem appearance] setTitleTextAttributes:attributes
                                                forState:UIControlStateNormal];

I was having a same problem and I did it this way.

--EDIT--

this is a solution when you really want to remove title text of all UIBarbuttonItem. If you only want to remove the title of the back bar button item, there is no one simple convenient solution. In my case, since I only have few UIBarButtonItems that need to show title text I just changed those specific buttons' titleTextAttributes. If you want to be more specific use the code below, which will only change navigation bar buttons:

NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                [UIColor clearColor],UITextAttributeTextColor,
                                nil];
    
[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTitleTextAttributes:attributes
                                                forState:UIControlStateNormal];

--EDIT-- for swift

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)
andylee
  • 255
  • 2
  • 6
3

This is using subclass navigationController removes the "Back".

I'm using this to remove it, permanently through the app.

//.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
0yeoj
  • 4,500
  • 3
  • 23
  • 41
3
[[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];
Bill Xie
  • 105
  • 6
2

Hide Back Button Title of Navigation Bar

UIBarButtonItem *barButton = [[UIBarButtonItem alloc] init];
barButton.title = @""; // blank or any other title
self.navigationController.navigationBar.topItem.backBarButtonItem = barButton;
Kirit Vaghela
  • 12,572
  • 4
  • 76
  • 80
2

Here's what I'm doing me, which is simpler to remove the title of back button

override func viewDidLoad() {
    super.viewDidLoad()
    navigationController?.navigationBar?.backItem?.title = ""
}
YanSte
  • 10,661
  • 3
  • 57
  • 53
2

Swift 3.1 You can do this by implementing the delegate method of UINavigationController. It'll hide the Title with back button only, we'll still get the back arrow image and default functionality.

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

You can also use this:

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

[temporaryBarButtonItem release];

This works for me

bogen
  • 9,954
  • 9
  • 50
  • 89
Utkarsh 786
  • 37
  • 1
  • 5
1
case : <Back as <

override func viewWillAppear(animated: Bool) {
navigationController!.navigationBar.topItem!.title = ""
    }
Alvin George
  • 14,148
  • 92
  • 64
1

Perfect solution globally

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
}
PeiweiChen
  • 413
  • 5
  • 16
1

I create a custom class for UINavigationController and apply it to all of the navigation controllers in my app. Inside this custom UINavigationController class I set the UINavigationBar delegate to self once the view loads.

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

Then I implement the delegate method:

- (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;
}

This way I simply assign my custom class to all my navigations controllers and it clears the title from all the back buttons. And just for clarity, I always set the title for all my other view controllers inside viewWillAppear so that the title is always updated just before the view appears (in case it is removed by tricks like this).

nurider
  • 1,555
  • 1
  • 18
  • 21
1

Just entering a single space for the Back button navigation item works!!

VirajP
  • 91
  • 1
  • 5
1

If like me you're using a custom view instead of the UINavigationBar and you're stuck with the back button then you have to do a bit of work that feels a bit cludgey.

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

It seems like if it doesn't get presented then no matter what it'll try show a title, this means it's shown then hidden before it's drawn and solves the problem.

Nicholas Smith
  • 11,642
  • 6
  • 37
  • 55
1
extension UIViewController{
    func hideBackButton(){
        navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
    }
}
Maor
  • 3,340
  • 3
  • 29
  • 38
1

This is better solution.

Other solution is dangerous because it's hack.

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)
    }
}
taku_oka
  • 453
  • 6
  • 18
1

If you want to remove the back button item title in iOS11, you can try it!

@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

Updated 2021: Use NXNavigationExtension

l1Dan
  • 9
  • 6
  • Thank you for this code snippet, which might provide some limited short-term help. A proper explanation [would greatly improve](//meta.stackexchange.com/q/114762) its long-term value by showing *why* this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you've made. – Toby Speight Jul 13 '18 at 12:06
0

I couldn't get it to work using Guto Araujo's answer of navigationBar.topItem.title = @"";

However, I was able to get the desired effect by setting self.title = @"" in the init method of my view controller. (Setting it in init is important, viewDidLoad won't work.)

zekel
  • 9,227
  • 10
  • 65
  • 96
0

I am listing out the solutions which worked for me so far.

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   



}
Alvin George
  • 14,148
  • 92
  • 64
0

Implement your own UIViewController base class and override 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

Now in any UIViewController where you want to set the title, you can just write self.title = @"MyTitle" as you normally would, and no text will appear on the back bar item when pushing a new UIViewController.

Avi
  • 826
  • 6
  • 16
0

I've made a very simple zero config category to hide all back button titles through out app you can check it out here. This question already has accepted answer, but for others it can be helpful.

EDIT:

.h file

#import <UIKit/UIKit.h>

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

@end

.m file

#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);
    }
}
Pratik Jamariya
  • 810
  • 1
  • 10
  • 35
0

In iOS 11 you can use the next code to hide back button title:

Swift:

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

This code doesn't remove title from navigation bar, but just makes it transparent, to back button still holds space for title. If you need to have more space for view controller title, then you need to use another solution.

Serhiy
  • 332
  • 6
  • 13
-1

Only need to set blank title text in ParentViewController.

self.navigationItem.title=@"";

If you need title text then Put below two methods in ParentViewController.

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

-(void)viewWillDisappear:(BOOL)animated
{
    self.navigationItem.title=@"";
}
Harshal Shah
  • 427
  • 3
  • 5
-2

This worked for me in iOS 7+:

In viewDidLoad:

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

Yes, that's a space between the quotes.

pizzafilms
  • 3,829
  • 4
  • 24
  • 39
-3

Just set offset for UIBarButtonItem appearance.

[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(-1000, -1000)
                                                     forBarMetrics:UIBarMetricsDefault];
landonandrey
  • 1,271
  • 1
  • 16
  • 26
  • 1
    It seems like the navbar title is still offset to make room for the back button text, even if it's not visible. – zekel Aug 07 '14 at 19:30