13

我有一个带有 4 个视图控制器的标签栏控制器,并且在导航控制器中有这个标签栏控制器。

我想为标签栏控制器的一个特定视图控制器显示 UIBarButtonItem。

我尝试使用以下

if (tabBarController.selectedViewController == customTourViewController)
    {
        [tabBarController.navigationItem setRightBarButtonItem:done];
    }

但是按钮不显示。

如果我将每个视图控制器都放在导航控制器中,那么按钮只会显示该视图,但我最终会有 2 个导航栏。

有什么办法可以实现第一个解决方案吗?谢谢。

4

3 回答 3

28

In my individual view controllers for the individual tabs, I have the following in the one that needs the button:

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
                                                                    style:UIBarButtonSystemItemDone target:nil action:nil];
    self.tabBarController.navigationItem.rightBarButtonItem = rightButton;
}

And in the view controllers that don't need the button, I have:

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    self.tabBarController.navigationItem.rightBarButtonItem = nil;
}

So, if it's not working for you, I'm not sure if it's your reference to tabBarController without the self designation (if I omit the self I get a compiler error). And where is this code because if it's in your tabBarController subclass, then you want self.navigationItem.rightBarButtonItem, right? Do you have your own ivar defined for that variable name? Or are you sure that done is defined properly (i.e. not nil)? Or are you sure this code is being called at all (perhaps set a breakpoint or insert a NSLog and make sure this code is being reached)?

于 2012-07-24T04:32:25.957 回答
6

或者,您可以在需要按钮的同一视图中实现 viewWillDisappear。

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];        
    self.tabBarController.navigationItem.rightBarButtonItem = nil;
}
于 2013-04-11T18:01:38.093 回答
1

上面接受的答案正是我所需要的,只是想将其转换为 Swift 以供将来使用。

我已将以下代码添加到需要栏按钮的视图控制器中(我为此示例创建了一个添加按钮):

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

self.tabBarController?.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: nil)
}

在不需要此条形按钮的视图控制器中,只需添加以下代码

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

self.tabBarController?.navigationItem.rightBarButtonItem = nil
}

您使用viewWillAppearViceviewDidAppear是因为您希望每次用户转到指定的视图控制器时都会出现条形按钮。

简单的说,viewDidAppear运行时调用一次,viewWillAppear每次访问视图控制器时都会调用。

于 2019-05-16T22:52:22.780 回答