UIToolBar - disable buttons

為{幸葍}努か 提交于 2021-02-04 14:49:08

问题


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.


回答1:


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.




回答2:


Fast enumeration to the rescue!

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


来源:https://stackoverflow.com/questions/768918/uitoolbar-disable-buttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!