Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 522
Ilya Suzdalnitski Avatar asked Apr 20 '09 16:04

Ilya Suzdalnitski


1 Answers

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.

like image 190
Alex Wayne Avatar answered Nov 15 '22 12:11

Alex Wayne