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

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


当前回答

可以在不改变其宽度或将其从工具条中移除的情况下将按钮隐藏在适当的位置。如果将样式设置为普通,删除标题并禁用按钮,则该按钮将消失。要恢复它,只需反转您的更改。

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

其他回答

我知道这个回答有点晚了。然而,如果其他人面临类似的情况,这可能会有所帮助。

在iOS 7中,要隐藏栏按钮项,我们可以使用以下两种技术:-

使用SetTitleTextAttributes:-这是伟大的酒吧按钮项目,如“完成”,“保存”等。然而,它不工作的项目,如添加,垃圾符号等(至少不是为我),因为他们不是文本。 使用TintColor:-如果我有一个栏按钮项目称为“deleteButton”:-

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

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

要再次显示按钮,我使用以下代码

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

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

例如:

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

2. 让uibuttas成为自定义视图。如:

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

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

3.你可以隐藏/取消隐藏你已经创建的myButton。(myButton setHidden:是的);

iOS 8。带有自定义图像的UIBarButtonItem。 我试过很多方法,但大多数都没用。 Max的解决方案,thesetTintColor没有改变为任何颜色。 这是我自己想出来的,我想它会对别人有用。

隐藏:

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

显示:

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

来自@lnafziger的回答

将你的Barbuttons保存在一个强大的outlet中,并这样隐藏/显示它:

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

当需要使用以下功能..

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

我目前正在运行OS X Yosemite开发者预览7和Xcode 6 beta 6,目标是iOS 7.1,以下解决方案对我来说很好:

为uinavigationitem和UIBarButtonItems创建outlet 运行以下代码删除 (自我。navItem setRightBarButtonItem: nil); (自我。navItem setLeftBarButtonItem: nil); 运行以下代码再次添加按钮 (自我。navItem setRightBarButtonItem deleteItem):; (自我。navItem setLeftBarButtonItem addItem):;