如何访问以编程方式创建的按钮?
问题描述:
我像这样在导航栏中添加了多个按钮。如何访问以编程方式创建的按钮?
UIToolbar* tools = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 133, 44.01)];
NSMutableArray* buttons = [[NSMutableArray alloc] initWithCapacity:2];
UIBarButtonItem *bi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(assignSelected)];
bi.style = UIBarButtonItemStyleBordered;
[bi setEnabled:FALSE];
[buttons addObject:bi];
[buttons addObject:self.editButtonItem];
[tools setItems:buttons animated:NO];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:tools];
self.editButtonItem.title = @"Select";
本质上我正在这样做,所以他们可以使用编辑按钮来选择一组项目,并对他们采取行动。我想启用在他们正在编辑时添加在那里的操作按钮。我有以下方法来控制编辑时按钮的说明。
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
[super setEditing:editing animated:animated];
if (editing)
{
self.editButtonItem.title = NSLocalizedString(@"Cancel", @"Cancel");
}
else
{
self.editButtonItem.title = NSLocalizedString(@"Select", @"Select");
}
}
这就是我要启用和禁用操作按钮的位置。我不知道如何访问该按钮,因为它是以编程方式创建的。
答
您应该可以通过您创建它的“bi”变量来访问它。 bi变量应该保存指向按钮的指针。所以,你可以调用该按钮的方法如下所示:
[bi methodName:methodArg];
想着你的问题多一点后,我认识你很可能具有不同的方法访问“双向”的问题。在头文件中设置UIBarButtonItem * bi,并将其等于零。 'UIBarButtonItem * bi = nil;'然后在你的实现文件中,离开类和指针,并从你的头文件初始化变量。 'bi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(assignSelected)];'然后类中的所有方法都可以访问它。 – Kyle 2012-04-25 22:17:04
这样一个明显的答案,我应该想到这一点。 – Jhorra 2012-04-25 22:26:17