如何显示/隐藏UIBarButtonItem?

时间:2021-04-04 22:21:08

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.

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

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).

UIBarButtonItem没有隐藏的财产,任何隐藏的例子我发现到目前为止涉及到导航栏按钮设置为零,我不认为我想要做的,因为我可能需要再次显示按钮(更不用说,如果我连接按钮一个IBOutlet,如果我设置为零我不知道我把它弄回来)。

33 个解决方案

#1


238  

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

将您的按钮保存在一个强大的outlet中(我们称之为myButton),并添加/删除它:

// 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.

因为它存储在outlet中,所以即使它不在工具栏上,也会保留对它的引用。

#2


173  

I know this answer is late for this question. However, it might help if anybody else faces a similar situation.

我知道这个问题的答案已经很晚了。然而,如果其他人面临类似的情况,可能会有所帮助。

In iOS 7, to hide a bar button item, we can use the following two techniques :-

在ios7中,为了隐藏一个栏按钮项,我们可以使用以下两种技术:-。

  • use SetTitleTextAttributes :- This works great on bar button items like "Done", "Save" etc. However, it does not work on items like Add, Trash symbol etc.(atleast not for me) since they are not texts.
  • 使用SetTitleTextAttributes:-在诸如“Done”、“Save”等栏按钮项目上,它的效果很好。但是,它不适用于添加、垃圾符号等项(至少对我来说不是这样),因为它们不是文本。
  • use TintColor :- If I have a bar button item called "deleteButton" :-
  • 使用TintColor:-如果我有一个名为“deleteButton”的栏按钮项目:-。

To hide the button, I used the following code:-

为了隐藏按钮,我使用了以下代码:-。

[self.deleteButton setEnabled:NO]; 
[self.deleteButton setTintColor: [UIColor clearColor]];

To show the button again I used the following code:-

为了再次显示这个按钮,我使用了以下代码:-。

[self.deleteButton setEnabled:YES];
[self.deleteButton setTintColor:nil];

#3


66  

Here's a simple approach:

这里有一个简单的方法:

hide:  barbuttonItem.width = 0.01;
show:  barbuttonItem.width = 0; //(0 defaults to normal button width, which is the width of the text)

I just ran it on my retina iPad, and .01 is small enough for it to not show up.

我只是在我的视网膜iPad上运行它,并且。01足够小,它不会出现。

#4


54  

It is possible to hide a button in place without changing its width or removing it from the bar. If you set the style to plain, remove the title, and disable the button, it will disappear. To restore it, just reverse your changes.

可以在不改变其宽度的情况下隐藏一个按钮,或者将其从酒吧中移除。如果您将样式设置为plain,删除标题,并禁用该按钮,它将消失。要恢复它,只需逆转您的更改。

-(void)toggleBarButton:(bool)show
{
    if (show) {
        btn.style = UIBarButtonItemStyleBordered;
        btn.enabled = true;
        btn.title = @"MyTitle";
    } else {
        btn.style = UIBarButtonItemStylePlain;
        btn.enabled = false;
        btn.title = nil;
    }
}

#5


39  

Below is my solution though i was looking it for Navigation Bar.

下面是我的解决方案,尽管我在寻找导航栏。

navBar.topItem.rightBarButtonItem = nil;

Here "navBar" is a IBOutlet to the NavigationBar in the view in XIB Here i wanted to hide the button or show it based on some condition. So i m testing for the condition in "If" and if true i am setting the button to nil in viewDidLoad method of the target view.

这里的“导航条”是在XIB视图中导航栏的IBOutlet,我想隐藏按钮,或者基于某种条件显示它。因此,我在“If”中测试条件,如果true我在目标视图的viewDidLoad方法中将按钮设置为nil。

This may not be relevant to your problem exactly but something similar incase if you want to hide buttons on NavigationBar

这可能与您的问题不相关,但如果您想在NavigationBar上隐藏按钮,就会出现类似的情况。

#6


21  

I am currently running OS X Yosemite Developer Preview 7 and Xcode 6 beta 6 targeting iOS 7.1 and following solution works fine for me:

我目前正在运行OS X Yosemite开发者预览7和Xcode 6 beta 6针对ios7.1,下面的解决方案对我来说很好:

  • Create outlet for UINavigationItemand UIBarButtonItems
  • 创建uinavigationitem和UIBarButtonItems的outlet。
  • Run following code to remove

    运行以下代码删除。

    [self.navItem setRightBarButtonItem:nil];
    [self.navItem setLeftBarButtonItem:nil];
    
  • Run following codes to add buttons again

    运行以下代码再次添加按钮。

    [self.navItem setRightBarButtonItem:deleteItem];
    [self.navItem setLeftBarButtonItem:addItem];
    

#7


14  

I used IBOutlets in my project. So my solution was:

我在我的项目中使用了iboutlet。所以我的解决方案是:

@IBOutlet weak var addBarButton: UIBarButtonItem!

addBarButton.enabled = false
addBarButton.tintColor = UIColor.clearColor()

And when you'll need to show this bar again, just set reversed properties.

当你需要再次显示这个栏时,设置反向属性。

In Swift 3 instead enable use isEnable property.

在Swift 3中,可以使用isEnable属性。

#8


14  

For Swift 3 and Swift 4 you can do this to hide the UIBarButtomItem:

对于Swift 3和Swift 4,你可以这样做来隐藏UIBarButtomItem:

self.deleteButton.isEnabled = false
self.deleteButton.tintColor = UIColor.clear

And to show the UIBarButtonItem:

并显示UIBarButtonItem:

self.deleteButton.isEnabled = true
self.deleteButton.tintColor = UIColor.blue

On the tintColor you must have to specify the origin color you are using for the UIBarButtomItem

在tintColor中,您必须指定用于UIBarButtomItem的源颜色。

#9


11  

iOS 8. UIBarButtonItem with custom image. Tried many different ways, most of them were not helping. Max's solution, thesetTintColor was not changing to any color. I figured out this one myself, thought it will be of use to some one.

iOS 8。UIBarButtonItem使用自定义图像。尝试了许多不同的方法,大多数都没有帮助。麦克斯的解决方案,这个颜色没有变到任何颜色。我自己想出了这个办法,认为它对某些人有用。

For Hiding:

隐藏:

[self.navigationItem.rightBarButtonItem setEnabled:NO];
[self.navigationItem.rightBarButtonItem setImage:nil];

For Showing:

显示:

[self.navigationItem.rightBarButtonItem setEnabled:YES];
[self.navigationItem.rightBarButtonItem setImage:image];

#10


11  

self.dismissButton.customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];

self.dismissButton。initWithFrame:CGRectMake(0,0,0,0)];

#11


9  

Try in Swift, don't update the tintColor if you have some design for your UIBarButtonItem like font size in AppDelegate, it will totally change the appearance of your button when showing up.

如果你的UIBarButtonItem(如AppDelegate的字体大小)有一些设计的话,不要更新tintColor,它会在出现时完全改变你的按钮的外观。

In case of a text button, changing title can let your button 'disappear'.

如果是文本按钮,更改标题可以让您的按钮“消失”。

if WANT_TO_SHOW {
    myBarButtonItem.enabled = true
    myBarButtonItem.title = "BUTTON_NAME"
}else{
    myBarButtonItem.enabled = false
    myBarButtonItem.title = ""
}

#12


5  

@IBDesignable class AttributedBarButtonItem: UIBarButtonItem {

    var isHidden: Bool = false {

        didSet {

            isEnabled = !isHidden
            tintColor = isHidden ? UIColor.clear : UIColor.black
        }
    }
}

And now simply change isHidden property.

现在,简单地改变一下被石头淹没的财产。

#13


4  

There is no way to "hide" a UIBarButtonItem you must remove it from the superView and add it back when you want to display it again.

没有办法“隐藏”UIBarButtonItem,您必须从父视图中删除它,并在您想要再次显示它时将它添加回来。

#14


4  

Improving From @lnafziger answer

改善从@lnafziger回答

Save your Barbuttons in a strong outlet and do this to hide/show it:

把你的按钮保存在一个强大的插座上,这样做是为了隐藏/显示它:

-(void) hideBarButtonItem :(UIBarButtonItem *)myButton {
    // Get the reference to the current toolbar buttons
    NSMutableArray *navBarBtns = [self.navigationItem.rightBarButtonItems mutableCopy];

    // This is how you remove the button from the toolbar and animate it
    [navBarBtns removeObject:myButton];
    [self.navigationItem setRightBarButtonItems:navBarBtns animated:YES];
}


-(void) showBarButtonItem :(UIBarButtonItem *)myButton {
    // Get the reference to the current toolbar buttons
    NSMutableArray *navBarBtns = [self.navigationItem.rightBarButtonItems mutableCopy];

    // This is how you add the button to the toolbar and animate it
    if (![navBarBtns containsObject:myButton]) {
        [navBarBtns addObject:myButton];
        [self.navigationItem setRightBarButtonItems:navBarBtns animated:YES];
    }
}

When ever required use below Function..

当需要使用以下功能时。

[self showBarButtonItem:self.rightBarBtn1];
[self hideBarButtonItem:self.rightBarBtn1];

#15


4  

This is long way down the answer list, but just in case somebody wants an easy copy and paste for the swift solution, here it is

这在答案列表中是很长的一段路,但是如果有人想要一个简单的复制和粘贴快速解决方案,就在这里。

func hideToolbarItem(button: UIBarButtonItem, withToolbar toolbar: UIToolbar) {
    var toolbarButtons: [UIBarButtonItem] = toolbar.items!
    toolbarButtons.removeAtIndex(toolbarButtons.indexOf(button)!)
    toolbar.setItems(toolbarButtons, animated: true)
}

func showToolbarItem(button: UIBarButtonItem, inToolbar toolbar: UIToolbar, atIndex index: Int) {
    var toolbarButtons: [UIBarButtonItem] = toolbar.items!
    if !toolbarButtons.contains(button) {
        toolbarButtons.insert(button, atIndex: index)
        toolbar.setItems(toolbarButtons, animated:true);
    }
}

#16


3  

One way to do it is use the initWithCustomView:(UIView *) property of when allocating the UIBarButtonItem. Subclass for UIView will have hide/unhide property.

一种方法是使用initWithCustomView:(UIView *)在分配UIBarButtonItem时的属性。UIView的子类将有隐藏/未隐藏属性。

For example:

例如:

1. Have a UIButton which you want to hide/unhide.

1。有一个你想隐藏/隐藏的UIButton。

2. Make the UIButtonas the custom view. Like :

2。将UIButtonas作为自定义视图。如:

UIButton*myButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];//your button

UIBarButtonItem*yourBarButton=[[UIBarButtonItem alloc] initWithCustomView:myButton];

3. You can hide/unhide the myButton you've created. [myButton setHidden:YES];

3所示。你可以隐藏/隐藏你创建的myButton。(myButton setHidden:是的);

#17


2  

Setting the text color to a clear color when the bar button item is disabled is probably a cleaner option. There's no weirdness that you have to explain in a comment. Also you don't destroy the button so you still keep any associated storyboard segues.

当禁用栏按钮项时,将文本颜色设置为清晰的颜色可能是一个更干净的选项。你必须在评论中解释,这并不奇怪。你也不破坏按钮,所以你仍然保留任何关联的故事板segue。

[self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor clearColor]}
                                                      forState:UIControlStateDisabled];

Then when ever you want the bar button item hidden, you can just do:

当你想要隐藏按钮项时,你可以这样做:

self.navigationItem.rightBarButton.enabled = NO;

It's lame there's no hidden property but this offers the same result.

虽然没有隐藏的财产,但这也提供了同样的结果。

#18


2  

In case the UIBarButtonItem has an image instead of the text in it you can do this to hide it: navigationBar.topItem.rightBarButtonItem.customView.alpha = 0.0;

如果UIBarButtonItem有一个图像而不是文本,你可以这样来隐藏它:navigationBar.topItem.rightBarButtonItem.customView。α= 0.0;

#19


2  

Some helper methods I thought I'd share based upon lnafziger's accepted answer as I have multiple toolbars and multiple buttons in each:

一些辅助方法,我认为我应该分享基于lnafziger的答案,因为我有多个工具栏和多个按钮:

-(void) hideToolbarItem:(UIBarButtonItem*) button inToolbar:(UIToolbar*) toolbar{
    NSMutableArray *toolbarButtons = [toolbar.items mutableCopy];
    [toolbarButtons removeObject:button];
    [toolbar setItems:toolbarButtons animated:NO];
}

-(void) showToolbarItem:(UIBarButtonItem*) button inToolbar:(UIToolbar*) toolbar atIndex:(int) index{
    NSMutableArray *toolbarButtons = [toolbar.items mutableCopy];
    if (![toolbarButtons containsObject:button]){
        [toolbarButtons insertObject:button atIndex:index];
        [self setToolbarItems:toolbarButtons animated:YES];
    }
}

#20


2  

You can easily get the view and hide it this way

您可以轻松地获取视图并将其隐藏。

let view: UIView = barButtonItem.valueForKey("view") as! UIView
view.hidden = true

#21


1  

Complementing Eli Burke`s response, if your UIBarButtonItemhas a background image instead of a title, you can use the code:

补充Eli Burke的回应,如果你的uibarbuttonitem有一个背景图片而不是标题,你可以使用代码:

-(void)toggleLogoutButton:(bool)show{
    if (show) {
        self.tabButton.style = UIBarButtonItemStyleBordered;
        self.tabButton.enabled = true;
        UIImage* imageMap = [UIImage imageNamed:@"btn_img.png"];
        [((UIButton *)[self.tabButton customView]) setBackgroundImage:imageMap forState:UIControlStateNormal];
    } else {
        self.tabButton.style = UIBarButtonItemStylePlain;
        self.tabButton.enabled = false;
        [((UIButton *)[self.tabButton customView]) setBackgroundImage:nil forState:UIControlStateNormal];
    }
}

#22


1  

For Swift version, here is the code:

对于Swift版本,以下是代码:

For UINavigationBar:

UINavigationBar:

self.navigationItem.rightBarButtonItem = nil

self.navigationItem.leftBarButtonItem = nil

#23


1  

If you are using Swift 3

如果你使用的是Swift 3。

if (ShowCondition){
   self.navigationItem.rightBarButtonItem = self.addAsset_btn 
 } 
else {
   self.navigationItem.rightBarButtonItem = nil
 }

#24


1  

I discovered another wrinkle in the tintColor and isEnabled approach suggested by Max and others - when VoiceOver is enabled for accessibility and the button is logically hidden, the accessibility cursor will still focus on the bar button, and state that it is "dimmed" (i.e. because isEnabled is set to false). The approach in the accepted answer doesn't suffer from this side-effect, but another work around I found was to set isAccessibilityElement to false when "hiding" the button:

我发现另一个皱纹tintColor isEnabled方法提出了麦克斯和其他人——当画外音启用了可访问性和逻辑上隐藏的按钮,可访问性光标仍集中在工具栏按钮,和状态,它是“黯淡”(即因为isEnabled设置为false)。在被接受的答案中,这种方法并没有受到这种副作用的影响,但我发现另一项工作是在“隐藏”按钮时将isAccessibilityElement设置为false:

deleteButton.tintColor = UIColor.clear
deleteButton.isEnabled = false
deleteButton.isAccessibilityElement = false

And then setting isAccessibilityElement back to true when "showing" the button:

然后在“显示”按钮时将isAccessibilityElement还原为true:

deleteButton.tintColor = UIColor.blue
deleteButton.isEnabled = true
deleteButton.isAccessibilityElement = true

Having the bar button item still take up space was not an issue in my case, since we were hiding/showing the left-most of right bar button items.

在我的例子中,拥有栏按钮项仍然占用空间不是问题,因为我们隐藏/显示了最左的右栏按钮项。

#25


0  

You need to manipulate the toolbar.items array.

您需要操作工具栏。条目数组。

Here is some code I use to hide and display a Done button. If your button is on the extreme edge of the toolbar or in-between other buttons your other buttons will move, so if you want your button to just disappear then place your button as the last button towards the centre. I animate the button move for effect, I quite like it.

下面是一些我用来隐藏和显示Done按钮的代码。如果你的按钮位于工具栏的最边缘或其他按钮之间,你的其他按钮将会移动,所以如果你想让你的按钮消失,那么将你的按钮作为最后一个按钮指向中心。我给按钮动了动画效果,我很喜欢。

-(void)initLibraryToolbar {

    libraryToolbarDocumentManagementEnabled = [NSMutableArray   arrayWithCapacity:self.libraryToolbar.items.count];
    libraryToolbarDocumentManagementDisabled = [NSMutableArray arrayWithCapacity:self.libraryToolbar.items.count];
    [libraryToolbarDocumentManagementEnabled addObjectsFromArray:self.libraryToolbar.items];
    [libraryToolbarDocumentManagementDisabled addObjectsFromArray:self.libraryToolbar.items];
    trashCan = [libraryToolbarDocumentManagementDisabled objectAtIndex:3];
    mail = [libraryToolbarDocumentManagementDisabled objectAtIndex:5];
    [libraryToolbarDocumentManagementDisabled removeObjectAtIndex:1];
    trashCan.enabled = NO;
    mail.enabled = NO;
    [self.libraryToolbar setItems:libraryToolbarDocumentManagementDisabled animated:NO];

}

}

so now can use the following code to show your button

现在可以使用下面的代码来显示您的按钮。

[self.libraryToolbar setItems:libraryToolbarDocumentManagementEnabled animated:YES];
trashCan.enabled = YES;
mail.enabled = YES; 

or to hide your button

或者隐藏你的按钮。

[self.libraryToolbar setItems:libraryToolbarDocumentManagementDisabled animated:YES];
trashCan.enabled = NO;
mail.enabled = NO;

#26


0  

In IB if you leave the button's title blank it will not appear (never initialized?). I do this often during development during UI updates if I want a bar button item to temp disappear for a build without deleting it and trashing all its outlet references.

在IB中,如果您将按钮的标题为空,它将不会出现(从未初始化?)。在UI更新期间,我经常这样做,如果我想让一个bar按钮项目在一个构建中消失,而不删除它,并将其所有的outlet引用删除。

This does not have the same effect during runtime, setting the button's title to nil will not cause it the whole button to disappear. Sorry doesn't really answer your question, but may be useful to some.

这在运行时不会产生相同的效果,将按钮的标题设为nil不会导致整个按钮消失。抱歉并不能真正回答你的问题,但可能对某些人有用。

Edit: This trick only works if the button's style is set to plain

编辑:这个技巧只在按钮的样式设置为普通时才有效。

#27


0  

I'll add my solution here as I couldn't find it mentioned here yet. I have a dynamic button whose image depends on the state of one control. The most simple solution for me was to set the image to nil if the control was not present. The image was updated each time the control updated and thus, this was optimal for me. Just to be sure I also set the enabled to NO.

我将在这里添加我的解决方案,因为我在这里还没有找到它。我有一个动态按钮,它的图像取决于一个控件的状态。对于我来说,最简单的解决方案是,如果控件不存在,则将图像设置为nil。每当控件更新时,图像都会被更新,这对我来说是最理想的。只是为了确保我也设置了NO。

Setting the width to a minimal value did not work on iOS 7.

将宽度设置为最小值在ios7上不起作用。

#28


0  

With credit to @lnafziger, @MindSpiker, @vishal, et. al,

有了@lnafziger的信用,@MindSpiker, @vishal,

The simplest one liner that I arrived at for a single right (or left) bar button is:

我到达的最简单的一个右(或左)栏按钮是:

self.navigationItem.rightBarButtonItem = <#StateExpression#>
    ? <#StrongPropertyButton#> : nil;

As in:

如:

@interface MyClass()

@property (strong, nonatomic) IBOutlet UIBarButtonItem *<#StrongPropertyButton#>;

@end

@implementation

- (void) updateState
{
    self.navigationItem.rightBarButtonItem = <#StateExpression#>
        ? <#StrongPropertyButton#> : nil;
}

@end

I tested this and it works for me (with the strong bar button item wired via IB).

我测试了这个,它对我有用(通过IB连接的强大的栏按钮项)。

#29


0  

Subclass UIBarButtonItem. Make sure the button in Interface Builder is set to HidableBarButtonItem. Make an outlet from the button to the view controller. From the view controller you can then hide/show the button by calling setHidden:

子类UIBarButtonItem。确保接口构建器中的按钮设置为HidableBarButtonItem。从按钮向视图控制器发出一个outlet。从视图控制器中,您可以通过调用setHidden来隐藏/显示按钮:

HidableBarButtonItem.h

HidableBarButtonItem.h

#import <UIKit/UIKit.h>

@interface HidableBarButtonItem : UIBarButtonItem

@property (nonatomic) BOOL hidden;

@end

HidableBarButtonItem.m

HidableBarButtonItem.m

#import "HidableBarButtonItem.h"

@implementation HidableBarButtonItem

- (void)setHidden:(BOOL const)hidden {
    _hidden = hidden;

    self.enabled = hidden ? YES : NO;
    self.tintColor = hidden ? [UIApplication sharedApplication].keyWindow.tintColor : [UIColor clearColor];
}

@end

#30


0  

I worked with xib and with UIToolbar. BarButtonItem was created in xib file. I created IBOutlet for BarButtonItem. And I used this code to hide my BarButtonItem

我和xib和UIToolbar一起工作。在xib文件中创建了BarButtonItem。我为BarButtonItem创建了IBOutlet。我用这段代码来隐藏我的BarButtonItem。

 self.myBarButtonItem.enabled = NO;
 self.myBarButtonItem.title =  nil;

this helped me.

这帮助了我。

#1


238  

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

将您的按钮保存在一个强大的outlet中(我们称之为myButton),并添加/删除它:

// 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.

因为它存储在outlet中,所以即使它不在工具栏上,也会保留对它的引用。

#2


173  

I know this answer is late for this question. However, it might help if anybody else faces a similar situation.

我知道这个问题的答案已经很晚了。然而,如果其他人面临类似的情况,可能会有所帮助。

In iOS 7, to hide a bar button item, we can use the following two techniques :-

在ios7中,为了隐藏一个栏按钮项,我们可以使用以下两种技术:-。

  • use SetTitleTextAttributes :- This works great on bar button items like "Done", "Save" etc. However, it does not work on items like Add, Trash symbol etc.(atleast not for me) since they are not texts.
  • 使用SetTitleTextAttributes:-在诸如“Done”、“Save”等栏按钮项目上,它的效果很好。但是,它不适用于添加、垃圾符号等项(至少对我来说不是这样),因为它们不是文本。
  • use TintColor :- If I have a bar button item called "deleteButton" :-
  • 使用TintColor:-如果我有一个名为“deleteButton”的栏按钮项目:-。

To hide the button, I used the following code:-

为了隐藏按钮,我使用了以下代码:-。

[self.deleteButton setEnabled:NO]; 
[self.deleteButton setTintColor: [UIColor clearColor]];

To show the button again I used the following code:-

为了再次显示这个按钮,我使用了以下代码:-。

[self.deleteButton setEnabled:YES];
[self.deleteButton setTintColor:nil];

#3


66  

Here's a simple approach:

这里有一个简单的方法:

hide:  barbuttonItem.width = 0.01;
show:  barbuttonItem.width = 0; //(0 defaults to normal button width, which is the width of the text)

I just ran it on my retina iPad, and .01 is small enough for it to not show up.

我只是在我的视网膜iPad上运行它,并且。01足够小,它不会出现。

#4


54  

It is possible to hide a button in place without changing its width or removing it from the bar. If you set the style to plain, remove the title, and disable the button, it will disappear. To restore it, just reverse your changes.

可以在不改变其宽度的情况下隐藏一个按钮,或者将其从酒吧中移除。如果您将样式设置为plain,删除标题,并禁用该按钮,它将消失。要恢复它,只需逆转您的更改。

-(void)toggleBarButton:(bool)show
{
    if (show) {
        btn.style = UIBarButtonItemStyleBordered;
        btn.enabled = true;
        btn.title = @"MyTitle";
    } else {
        btn.style = UIBarButtonItemStylePlain;
        btn.enabled = false;
        btn.title = nil;
    }
}

#5


39  

Below is my solution though i was looking it for Navigation Bar.

下面是我的解决方案,尽管我在寻找导航栏。

navBar.topItem.rightBarButtonItem = nil;

Here "navBar" is a IBOutlet to the NavigationBar in the view in XIB Here i wanted to hide the button or show it based on some condition. So i m testing for the condition in "If" and if true i am setting the button to nil in viewDidLoad method of the target view.

这里的“导航条”是在XIB视图中导航栏的IBOutlet,我想隐藏按钮,或者基于某种条件显示它。因此,我在“If”中测试条件,如果true我在目标视图的viewDidLoad方法中将按钮设置为nil。

This may not be relevant to your problem exactly but something similar incase if you want to hide buttons on NavigationBar

这可能与您的问题不相关,但如果您想在NavigationBar上隐藏按钮,就会出现类似的情况。

#6


21  

I am currently running OS X Yosemite Developer Preview 7 and Xcode 6 beta 6 targeting iOS 7.1 and following solution works fine for me:

我目前正在运行OS X Yosemite开发者预览7和Xcode 6 beta 6针对ios7.1,下面的解决方案对我来说很好:

  • Create outlet for UINavigationItemand UIBarButtonItems
  • 创建uinavigationitem和UIBarButtonItems的outlet。
  • Run following code to remove

    运行以下代码删除。

    [self.navItem setRightBarButtonItem:nil];
    [self.navItem setLeftBarButtonItem:nil];
    
  • Run following codes to add buttons again

    运行以下代码再次添加按钮。

    [self.navItem setRightBarButtonItem:deleteItem];
    [self.navItem setLeftBarButtonItem:addItem];
    

#7


14  

I used IBOutlets in my project. So my solution was:

我在我的项目中使用了iboutlet。所以我的解决方案是:

@IBOutlet weak var addBarButton: UIBarButtonItem!

addBarButton.enabled = false
addBarButton.tintColor = UIColor.clearColor()

And when you'll need to show this bar again, just set reversed properties.

当你需要再次显示这个栏时,设置反向属性。

In Swift 3 instead enable use isEnable property.

在Swift 3中,可以使用isEnable属性。

#8


14  

For Swift 3 and Swift 4 you can do this to hide the UIBarButtomItem:

对于Swift 3和Swift 4,你可以这样做来隐藏UIBarButtomItem:

self.deleteButton.isEnabled = false
self.deleteButton.tintColor = UIColor.clear

And to show the UIBarButtonItem:

并显示UIBarButtonItem:

self.deleteButton.isEnabled = true
self.deleteButton.tintColor = UIColor.blue

On the tintColor you must have to specify the origin color you are using for the UIBarButtomItem

在tintColor中,您必须指定用于UIBarButtomItem的源颜色。

#9


11  

iOS 8. UIBarButtonItem with custom image. Tried many different ways, most of them were not helping. Max's solution, thesetTintColor was not changing to any color. I figured out this one myself, thought it will be of use to some one.

iOS 8。UIBarButtonItem使用自定义图像。尝试了许多不同的方法,大多数都没有帮助。麦克斯的解决方案,这个颜色没有变到任何颜色。我自己想出了这个办法,认为它对某些人有用。

For Hiding:

隐藏:

[self.navigationItem.rightBarButtonItem setEnabled:NO];
[self.navigationItem.rightBarButtonItem setImage:nil];

For Showing:

显示:

[self.navigationItem.rightBarButtonItem setEnabled:YES];
[self.navigationItem.rightBarButtonItem setImage:image];

#10


11  

self.dismissButton.customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];

self.dismissButton。initWithFrame:CGRectMake(0,0,0,0)];

#11


9  

Try in Swift, don't update the tintColor if you have some design for your UIBarButtonItem like font size in AppDelegate, it will totally change the appearance of your button when showing up.

如果你的UIBarButtonItem(如AppDelegate的字体大小)有一些设计的话,不要更新tintColor,它会在出现时完全改变你的按钮的外观。

In case of a text button, changing title can let your button 'disappear'.

如果是文本按钮,更改标题可以让您的按钮“消失”。

if WANT_TO_SHOW {
    myBarButtonItem.enabled = true
    myBarButtonItem.title = "BUTTON_NAME"
}else{
    myBarButtonItem.enabled = false
    myBarButtonItem.title = ""
}

#12


5  

@IBDesignable class AttributedBarButtonItem: UIBarButtonItem {

    var isHidden: Bool = false {

        didSet {

            isEnabled = !isHidden
            tintColor = isHidden ? UIColor.clear : UIColor.black
        }
    }
}

And now simply change isHidden property.

现在,简单地改变一下被石头淹没的财产。

#13


4  

There is no way to "hide" a UIBarButtonItem you must remove it from the superView and add it back when you want to display it again.

没有办法“隐藏”UIBarButtonItem,您必须从父视图中删除它,并在您想要再次显示它时将它添加回来。

#14


4  

Improving From @lnafziger answer

改善从@lnafziger回答

Save your Barbuttons in a strong outlet and do this to hide/show it:

把你的按钮保存在一个强大的插座上,这样做是为了隐藏/显示它:

-(void) hideBarButtonItem :(UIBarButtonItem *)myButton {
    // Get the reference to the current toolbar buttons
    NSMutableArray *navBarBtns = [self.navigationItem.rightBarButtonItems mutableCopy];

    // This is how you remove the button from the toolbar and animate it
    [navBarBtns removeObject:myButton];
    [self.navigationItem setRightBarButtonItems:navBarBtns animated:YES];
}


-(void) showBarButtonItem :(UIBarButtonItem *)myButton {
    // Get the reference to the current toolbar buttons
    NSMutableArray *navBarBtns = [self.navigationItem.rightBarButtonItems mutableCopy];

    // This is how you add the button to the toolbar and animate it
    if (![navBarBtns containsObject:myButton]) {
        [navBarBtns addObject:myButton];
        [self.navigationItem setRightBarButtonItems:navBarBtns animated:YES];
    }
}

When ever required use below Function..

当需要使用以下功能时。

[self showBarButtonItem:self.rightBarBtn1];
[self hideBarButtonItem:self.rightBarBtn1];

#15


4  

This is long way down the answer list, but just in case somebody wants an easy copy and paste for the swift solution, here it is

这在答案列表中是很长的一段路,但是如果有人想要一个简单的复制和粘贴快速解决方案,就在这里。

func hideToolbarItem(button: UIBarButtonItem, withToolbar toolbar: UIToolbar) {
    var toolbarButtons: [UIBarButtonItem] = toolbar.items!
    toolbarButtons.removeAtIndex(toolbarButtons.indexOf(button)!)
    toolbar.setItems(toolbarButtons, animated: true)
}

func showToolbarItem(button: UIBarButtonItem, inToolbar toolbar: UIToolbar, atIndex index: Int) {
    var toolbarButtons: [UIBarButtonItem] = toolbar.items!
    if !toolbarButtons.contains(button) {
        toolbarButtons.insert(button, atIndex: index)
        toolbar.setItems(toolbarButtons, animated:true);
    }
}

#16


3  

One way to do it is use the initWithCustomView:(UIView *) property of when allocating the UIBarButtonItem. Subclass for UIView will have hide/unhide property.

一种方法是使用initWithCustomView:(UIView *)在分配UIBarButtonItem时的属性。UIView的子类将有隐藏/未隐藏属性。

For example:

例如:

1. Have a UIButton which you want to hide/unhide.

1。有一个你想隐藏/隐藏的UIButton。

2. Make the UIButtonas the custom view. Like :

2。将UIButtonas作为自定义视图。如:

UIButton*myButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];//your button

UIBarButtonItem*yourBarButton=[[UIBarButtonItem alloc] initWithCustomView:myButton];

3. You can hide/unhide the myButton you've created. [myButton setHidden:YES];

3所示。你可以隐藏/隐藏你创建的myButton。(myButton setHidden:是的);

#17


2  

Setting the text color to a clear color when the bar button item is disabled is probably a cleaner option. There's no weirdness that you have to explain in a comment. Also you don't destroy the button so you still keep any associated storyboard segues.

当禁用栏按钮项时,将文本颜色设置为清晰的颜色可能是一个更干净的选项。你必须在评论中解释,这并不奇怪。你也不破坏按钮,所以你仍然保留任何关联的故事板segue。

[self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor clearColor]}
                                                      forState:UIControlStateDisabled];

Then when ever you want the bar button item hidden, you can just do:

当你想要隐藏按钮项时,你可以这样做:

self.navigationItem.rightBarButton.enabled = NO;

It's lame there's no hidden property but this offers the same result.

虽然没有隐藏的财产,但这也提供了同样的结果。

#18


2  

In case the UIBarButtonItem has an image instead of the text in it you can do this to hide it: navigationBar.topItem.rightBarButtonItem.customView.alpha = 0.0;

如果UIBarButtonItem有一个图像而不是文本,你可以这样来隐藏它:navigationBar.topItem.rightBarButtonItem.customView。α= 0.0;

#19


2  

Some helper methods I thought I'd share based upon lnafziger's accepted answer as I have multiple toolbars and multiple buttons in each:

一些辅助方法,我认为我应该分享基于lnafziger的答案,因为我有多个工具栏和多个按钮:

-(void) hideToolbarItem:(UIBarButtonItem*) button inToolbar:(UIToolbar*) toolbar{
    NSMutableArray *toolbarButtons = [toolbar.items mutableCopy];
    [toolbarButtons removeObject:button];
    [toolbar setItems:toolbarButtons animated:NO];
}

-(void) showToolbarItem:(UIBarButtonItem*) button inToolbar:(UIToolbar*) toolbar atIndex:(int) index{
    NSMutableArray *toolbarButtons = [toolbar.items mutableCopy];
    if (![toolbarButtons containsObject:button]){
        [toolbarButtons insertObject:button atIndex:index];
        [self setToolbarItems:toolbarButtons animated:YES];
    }
}

#20


2  

You can easily get the view and hide it this way

您可以轻松地获取视图并将其隐藏。

let view: UIView = barButtonItem.valueForKey("view") as! UIView
view.hidden = true

#21


1  

Complementing Eli Burke`s response, if your UIBarButtonItemhas a background image instead of a title, you can use the code:

补充Eli Burke的回应,如果你的uibarbuttonitem有一个背景图片而不是标题,你可以使用代码:

-(void)toggleLogoutButton:(bool)show{
    if (show) {
        self.tabButton.style = UIBarButtonItemStyleBordered;
        self.tabButton.enabled = true;
        UIImage* imageMap = [UIImage imageNamed:@"btn_img.png"];
        [((UIButton *)[self.tabButton customView]) setBackgroundImage:imageMap forState:UIControlStateNormal];
    } else {
        self.tabButton.style = UIBarButtonItemStylePlain;
        self.tabButton.enabled = false;
        [((UIButton *)[self.tabButton customView]) setBackgroundImage:nil forState:UIControlStateNormal];
    }
}

#22


1  

For Swift version, here is the code:

对于Swift版本,以下是代码:

For UINavigationBar:

UINavigationBar:

self.navigationItem.rightBarButtonItem = nil

self.navigationItem.leftBarButtonItem = nil

#23


1  

If you are using Swift 3

如果你使用的是Swift 3。

if (ShowCondition){
   self.navigationItem.rightBarButtonItem = self.addAsset_btn 
 } 
else {
   self.navigationItem.rightBarButtonItem = nil
 }

#24


1  

I discovered another wrinkle in the tintColor and isEnabled approach suggested by Max and others - when VoiceOver is enabled for accessibility and the button is logically hidden, the accessibility cursor will still focus on the bar button, and state that it is "dimmed" (i.e. because isEnabled is set to false). The approach in the accepted answer doesn't suffer from this side-effect, but another work around I found was to set isAccessibilityElement to false when "hiding" the button:

我发现另一个皱纹tintColor isEnabled方法提出了麦克斯和其他人——当画外音启用了可访问性和逻辑上隐藏的按钮,可访问性光标仍集中在工具栏按钮,和状态,它是“黯淡”(即因为isEnabled设置为false)。在被接受的答案中,这种方法并没有受到这种副作用的影响,但我发现另一项工作是在“隐藏”按钮时将isAccessibilityElement设置为false:

deleteButton.tintColor = UIColor.clear
deleteButton.isEnabled = false
deleteButton.isAccessibilityElement = false

And then setting isAccessibilityElement back to true when "showing" the button:

然后在“显示”按钮时将isAccessibilityElement还原为true:

deleteButton.tintColor = UIColor.blue
deleteButton.isEnabled = true
deleteButton.isAccessibilityElement = true

Having the bar button item still take up space was not an issue in my case, since we were hiding/showing the left-most of right bar button items.

在我的例子中,拥有栏按钮项仍然占用空间不是问题,因为我们隐藏/显示了最左的右栏按钮项。

#25


0  

You need to manipulate the toolbar.items array.

您需要操作工具栏。条目数组。

Here is some code I use to hide and display a Done button. If your button is on the extreme edge of the toolbar or in-between other buttons your other buttons will move, so if you want your button to just disappear then place your button as the last button towards the centre. I animate the button move for effect, I quite like it.

下面是一些我用来隐藏和显示Done按钮的代码。如果你的按钮位于工具栏的最边缘或其他按钮之间,你的其他按钮将会移动,所以如果你想让你的按钮消失,那么将你的按钮作为最后一个按钮指向中心。我给按钮动了动画效果,我很喜欢。

-(void)initLibraryToolbar {

    libraryToolbarDocumentManagementEnabled = [NSMutableArray   arrayWithCapacity:self.libraryToolbar.items.count];
    libraryToolbarDocumentManagementDisabled = [NSMutableArray arrayWithCapacity:self.libraryToolbar.items.count];
    [libraryToolbarDocumentManagementEnabled addObjectsFromArray:self.libraryToolbar.items];
    [libraryToolbarDocumentManagementDisabled addObjectsFromArray:self.libraryToolbar.items];
    trashCan = [libraryToolbarDocumentManagementDisabled objectAtIndex:3];
    mail = [libraryToolbarDocumentManagementDisabled objectAtIndex:5];
    [libraryToolbarDocumentManagementDisabled removeObjectAtIndex:1];
    trashCan.enabled = NO;
    mail.enabled = NO;
    [self.libraryToolbar setItems:libraryToolbarDocumentManagementDisabled animated:NO];

}

}

so now can use the following code to show your button

现在可以使用下面的代码来显示您的按钮。

[self.libraryToolbar setItems:libraryToolbarDocumentManagementEnabled animated:YES];
trashCan.enabled = YES;
mail.enabled = YES; 

or to hide your button

或者隐藏你的按钮。

[self.libraryToolbar setItems:libraryToolbarDocumentManagementDisabled animated:YES];
trashCan.enabled = NO;
mail.enabled = NO;

#26


0  

In IB if you leave the button's title blank it will not appear (never initialized?). I do this often during development during UI updates if I want a bar button item to temp disappear for a build without deleting it and trashing all its outlet references.

在IB中,如果您将按钮的标题为空,它将不会出现(从未初始化?)。在UI更新期间,我经常这样做,如果我想让一个bar按钮项目在一个构建中消失,而不删除它,并将其所有的outlet引用删除。

This does not have the same effect during runtime, setting the button's title to nil will not cause it the whole button to disappear. Sorry doesn't really answer your question, but may be useful to some.

这在运行时不会产生相同的效果,将按钮的标题设为nil不会导致整个按钮消失。抱歉并不能真正回答你的问题,但可能对某些人有用。

Edit: This trick only works if the button's style is set to plain

编辑:这个技巧只在按钮的样式设置为普通时才有效。

#27


0  

I'll add my solution here as I couldn't find it mentioned here yet. I have a dynamic button whose image depends on the state of one control. The most simple solution for me was to set the image to nil if the control was not present. The image was updated each time the control updated and thus, this was optimal for me. Just to be sure I also set the enabled to NO.

我将在这里添加我的解决方案,因为我在这里还没有找到它。我有一个动态按钮,它的图像取决于一个控件的状态。对于我来说,最简单的解决方案是,如果控件不存在,则将图像设置为nil。每当控件更新时,图像都会被更新,这对我来说是最理想的。只是为了确保我也设置了NO。

Setting the width to a minimal value did not work on iOS 7.

将宽度设置为最小值在ios7上不起作用。

#28


0  

With credit to @lnafziger, @MindSpiker, @vishal, et. al,

有了@lnafziger的信用,@MindSpiker, @vishal,

The simplest one liner that I arrived at for a single right (or left) bar button is:

我到达的最简单的一个右(或左)栏按钮是:

self.navigationItem.rightBarButtonItem = <#StateExpression#>
    ? <#StrongPropertyButton#> : nil;

As in:

如:

@interface MyClass()

@property (strong, nonatomic) IBOutlet UIBarButtonItem *<#StrongPropertyButton#>;

@end

@implementation

- (void) updateState
{
    self.navigationItem.rightBarButtonItem = <#StateExpression#>
        ? <#StrongPropertyButton#> : nil;
}

@end

I tested this and it works for me (with the strong bar button item wired via IB).

我测试了这个,它对我有用(通过IB连接的强大的栏按钮项)。

#29


0  

Subclass UIBarButtonItem. Make sure the button in Interface Builder is set to HidableBarButtonItem. Make an outlet from the button to the view controller. From the view controller you can then hide/show the button by calling setHidden:

子类UIBarButtonItem。确保接口构建器中的按钮设置为HidableBarButtonItem。从按钮向视图控制器发出一个outlet。从视图控制器中,您可以通过调用setHidden来隐藏/显示按钮:

HidableBarButtonItem.h

HidableBarButtonItem.h

#import <UIKit/UIKit.h>

@interface HidableBarButtonItem : UIBarButtonItem

@property (nonatomic) BOOL hidden;

@end

HidableBarButtonItem.m

HidableBarButtonItem.m

#import "HidableBarButtonItem.h"

@implementation HidableBarButtonItem

- (void)setHidden:(BOOL const)hidden {
    _hidden = hidden;

    self.enabled = hidden ? YES : NO;
    self.tintColor = hidden ? [UIApplication sharedApplication].keyWindow.tintColor : [UIColor clearColor];
}

@end

#30


0  

I worked with xib and with UIToolbar. BarButtonItem was created in xib file. I created IBOutlet for BarButtonItem. And I used this code to hide my BarButtonItem

我和xib和UIToolbar一起工作。在xib文件中创建了BarButtonItem。我为BarButtonItem创建了IBOutlet。我用这段代码来隐藏我的BarButtonItem。

 self.myBarButtonItem.enabled = NO;
 self.myBarButtonItem.title =  nil;

this helped me.

这帮助了我。