UIToolBar - 禁用按钮

时间:2009-04-20 16:03:06

标签: iphone cocoa-touch

在我的应用程序中我有一个工具栏,在某一点上我想禁用或启用一些按钮。最简单的方法是什么?如何访问UIToolbar的items属性?

这是我的代码:

-(void)addToolbar {
    NSMutableArray *buttons = [[NSMutableArray alloc] init]; 

    //Define space
    UIBarButtonItem *flexibleSpaceItem; 
    flexibleSpaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target:nil action:NULL]; 

    //Add "new" button
    UIBarButtonItem *newButton = [[UIBarButtonItem alloc]
                                  initWithTitle:@"New" style:UIBarButtonItemStyleBordered target:self action:@selector(new_clicked)];
    [buttons addObject:newButton];
    [newButton release];

    //Add space
    [buttons addObject:flexibleSpaceItem];

    //Add "make active" button
    UIBarButtonItem *activeButton = [[UIBarButtonItem alloc]
                                  initWithTitle:@"Make Active" style:UIBarButtonItemStyleBordered target:self action:@selector(make_active_clicked)];
    [buttons addObject:activeButton];
    [activeButton release];

    [buttons addObject:flexibleSpaceItem];

    //Add "edit" button
    UIBarButtonItem *editButton = [[UIBarButtonItem alloc]
                                  initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(edit_clicked)];
    [buttons addObject:editButton];
    [editButton release];

    [flexibleSpaceItem release];

    [toolBar setItems:buttons];
    [buttons release];
}

提前谢谢。

2 个答案:

答案 0 :(得分:14)

最简单的方法是将对UIBarButtonItem的引用保存为实例变量。

# header file
UIBarButtonItem *editButton;

然后您的代码变为

# .m file
editButton = [[UIBarButtonItem alloc]
               initWithTitle:@"Edit"
               style:UIBarButtonItemStyleBordered
               target:self
               action:@selector(edit_clicked)];
[buttons addObject:editbutton];

现在,在任何实例方法的任何地方,禁用按钮都非常简单:

editButton.enabled = NO;

也不要立即release,因为这个类现在拥有按钮对象。因此,release方法dealloc代替它。

答案 1 :(得分:6)

Fast enumeration救援!

- (void) setToolbarButtonsEnabled:(BOOL)enabled
{
    for (UIBarButtonItem *item in self.toolbarItems)
    {
        item.enabled = !enabled;
    }
}