Ilya Suzdalnitski
Ilya Suzdalnitski

Reputation: 53560

UIToolBar - disable buttons

in my app I have a toolbar and at a certain point I want to disable or enable some buttons. What is the easiest way to do so? How can I access items property of UIToolbar?

Here is my code:

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

Thank you in advance.

Upvotes: 11

Views: 10150

Answers (2)

memmons
memmons

Reputation: 40502

Fast enumeration to the rescue!

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

Upvotes: 6

Alex Wayne
Alex Wayne

Reputation: 187134

The simplest way is to save a reference to the UIBarButtonItem as an instance variable.

# header file
UIBarButtonItem *editButton;

Then your code becomes

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

Now anywhere in any instance method, disabling the button is as simple as:

editButton.enabled = NO;

Also dont release it immediately, since this class now owns the button object. So release it in the dealloc method instead.

Upvotes: 14

Related Questions