我在IB中创建了一个带有几个按钮的工具栏。我想能够隐藏/显示一个按钮取决于数据的状态在主窗口。
UIBarButtonItem没有隐藏属性,到目前为止我发现的任何隐藏它们的例子都涉及将导航栏按钮设置为nil,我不认为我想在这里做,因为我可能需要再次显示按钮(更不用说,如果我连接我的按钮到IBOutlet,如果我设置为nil,我不确定我如何得到它)。
我在IB中创建了一个带有几个按钮的工具栏。我想能够隐藏/显示一个按钮取决于数据的状态在主窗口。
UIBarButtonItem没有隐藏属性,到目前为止我发现的任何隐藏它们的例子都涉及将导航栏按钮设置为nil,我不认为我想在这里做,因为我可能需要再次显示按钮(更不用说,如果我连接我的按钮到IBOutlet,如果我设置为nil,我不确定我如何得到它)。
当前回答
将你的按钮保存在一个强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];
}
因为它存储在输出中,所以即使它不在工具栏上,您也将保留对它的引用。
其他回答
@IBDesignable class AttributedBarButtonItem: UIBarButtonItem {
var isHidden: Bool = false {
didSet {
isEnabled = !isHidden
tintColor = isHidden ? UIColor.clear : UIColor.black
}
}
}
现在只需改变isHidden属性。
归功于@lnafziger、@MindSpiker、@vishal等。都
我为单个右(或左)栏按钮设计的最简单的一行代码是:
self.navigationItem.rightBarButtonItem = <#StateExpression#>
? <#StrongPropertyButton#> : nil;
如:
@interface MyClass()
@property (strong, nonatomic) IBOutlet UIBarButtonItem *<#StrongPropertyButton#>;
@end
@implementation
- (void) updateState
{
self.navigationItem.rightBarButtonItem = <#StateExpression#>
? <#StrongPropertyButton#> : nil;
}
@end
我测试了这个,它为我工作(与强栏按钮项目有线通过IB)。
我的解是设定边界。宽度为0,你有什么UIBarButtonItem(我使用这种方法与UIButton和UISearchBar):
隐藏:
self.btnXXX.bounds = CGRectMake(0,0,0,0);
显示:
self.btnXXX.bounds = CGRectMake(0,0,40,30); // <-- put your sizes here
我将在这里添加我的解决方案,因为我还没有在这里找到它。我有一个动态按钮,其图像取决于一个控件的状态。对我来说,最简单的解决方案是,如果控件不存在,将图像设置为nil。每次控件更新时,图像都会更新,因此,这对我来说是最优的。为了确保我也设置了enabled为NO。
将宽度设置为最小值在iOS 7上不起作用。
子类UIBarButtonItem。 确保界面构建器中的按钮设置为HidableBarButtonItem。 创建一个从按钮到视图控制器的outlet。在视图控制器中,你可以通过调用setHidden来隐藏/显示按钮:
HidableBarButtonItem。h
#import <UIKit/UIKit.h>
@interface HidableBarButtonItem : UIBarButtonItem
@property (nonatomic) BOOL hidden;
@end
公元HidableBarButtonItem。
#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