如何显示/隐藏UIBarButtonItem? [英] How do I show/hide a UIBarButtonItem?

查看:657
本文介绍了如何显示/隐藏UIBarButtonItem?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在IB中创建了一个带有几个按钮的工具栏。我希望能够隐藏/显示其中一个按钮,具体取决于主窗口中的数据状态。

I created a toolbar in IB with several buttons. I would like to be able to hide/show one of the buttons depending on the state of the data in the main window.

UIBarButtonItem 没有隐藏属性,到目前为止我发现的任何隐藏属性的例子都涉及到将导航栏按钮设置为nil,我不认为我想在这里做,因为我可能需要再次显示按钮(更不用说,如果我将我的按钮连接到IBOutlet,如果我将其设置为nil I'我不知道怎么回来。)

UIBarButtonItem doesn't have a hidden property, and any examples I've found so far for hiding them involve setting nav bar buttons to nil, which I don't think I want to do here because I may need to show the button again (not to mention that, if I connect my button to an IBOutlet, if I set that to nil I'm not sure how I'd get it back).

推荐答案

将按钮保存在强大中outlet(让我们称之为 myButton )并执行此操作添加/删除它:

Save your button in a strong outlet (let's call it myButton) and do this to add/remove it:

// Get the reference to the current toolbar buttons
NSMutableArray *toolbarButtons = [self.toolbarItems mutableCopy];

// This is how you remove the button from the toolbar and animate it
[toolbarButtons removeObject:self.myButton];
[self setToolbarItems:toolbarButtons animated:YES];

// This is how you add the button to the toolbar and animate it
if (![toolbarButtons containsObject:self.myButton]) {
    // The following line adds the object to the end of the array.  
    // If you want to add the button somewhere else, use the `insertObject:atIndex:` 
    // method instead of the `addObject` method.
    [toolbarButtons addObject:self.myButton];
    [self setToolbarItems:toolbarButtons animated:YES];
}

因为它存储在插座中,所以你会保留对它的引用当它不在工具栏上时。

Because it is stored in the outlet, you will keep a reference to it even when it isn't on the toolbar.

这篇关于如何显示/隐藏UIBarButtonItem?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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