Hiding UINavigationItem's bar button

2019-02-12 00:07发布

I have added a BarButton item to the left of the nav.bar through Interface Builder and in the code I want this only to show in my table view's edit mode. But I didn't find any hidden property to set the leftBarButtonItem (like: self.navigationItem.leftBarButtonItem.hidden = YES).

I can only set enabled property. Anybody know how to control the hide and show property of the leftBarButtonItem, please help.

10条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-02-12 00:45

To hide/disable

[self.navigationItem.leftBarButtonItem setEnabled:FALSE];

To show/enable

[self.navigationItem.leftBarButtonItem setEnabled:TRUE];
查看更多
叼着烟拽天下
3楼-- · 2019-02-12 00:47

This solution work for me

UIView *myView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, 300, 30)];
UIBarButtonItem *btnL = [[UIBarButtonItem alloc]initWithCustomView:myView];
self.navigationItem.leftBarButtonItem = btnL;
查看更多
smile是对你的礼貌
4楼-- · 2019-02-12 00:48

There's nothing in the documentation to suggest bar items have a hidden property.

Why not set

self.navigationItem.leftBarButtonItem = nil; 

when the user isn't editing, then set

self.navigationItem.leftBarButtonItem = whateverBarButtonItem; 

when the user is editing? This requires either re-creating the button each time or storing it for the duration of the view's lifecycle. Neither is terribly painful, but no, not nearly as easy as a .hidden property.

查看更多
Deceive 欺骗
5楼-- · 2019-02-12 00:49

I just created my own "hide" function show below:

- (void)hideClearButton:(BOOL)hide {

    if (hide) {
        self.navigationItem.leftBarButtonItem = nil;
    }
    else {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]
                                                 initWithTitle:NSLocalizedString(@"Clear", @"Recents")
                                                 style:UIBarButtonItemStylePlain
                                                 target:self action:@selector(clearAll:)];

    }
}

You can just call it like:

[self hideClearButton:YES]; //hide it

or

[self hideClearButton:NO];  //show it
查看更多
贼婆χ
6楼-- · 2019-02-12 00:50

You can use

// Hide
self.navigationItem.leftBarButtonItem = nil;

// Show
self.navigationItem.leftBarButtonItem = self.myBarButtonItem

The key is making sure that you have a strong reference to the button item before nilling leftBarButtonItem.

@property (strong, nonatomic) IBOutlet UIBarButtonItem *myBarButtonItem;
查看更多
Fickle 薄情
7楼-- · 2019-02-12 00:56

I'm pretty sure the only way to "hide" it is to nil it out.

self.navigationItem.leftBarButtonItem = nil;

Though it's not a perfect answer to your question, since that basically gets rid of your button instead of hiding it. You'll either have to recreate it or keep your original button around and simply set the leftBarButtonItem back to your UIBarButtonItem.

查看更多
登录 后发表回答