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

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


当前回答

我的答案是斯威夫特!

if $0 {
    self.navigationItem.rightBarButtonItems = [UIBarButtonItem(customView: self.button1)]
} else {
    self.navigationItem.rightBarButtonItems = [UIBarButtonItem(customView: self.button2)]
}

其他回答

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

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

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

@IBOutlet weak var addBarButton: UIBarButtonItem!

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

当您需要再次显示此栏时,只需设置反转属性。

在Swift 3中使用isEnable属性。

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

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

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

为了显示UIBarButtonItem:

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

在tintColor上,你必须指定UIBarButtomItem使用的原始颜色