How do I show/hide a UIBarButtonItem?

前端 未结 30 2319
执念已碎
执念已碎 2020-11-28 01:18

I created a toolbar in IB with several buttons. I would like to be able to hide/show one of the buttons depending on the state of the data in the main window.

30条回答
  •  醉话见心
    2020-11-28 02:13

    Improving From @lnafziger answer

    Save your Barbuttons in a strong outlet and do this to hide/show it:

    -(void) hideBarButtonItem :(UIBarButtonItem *)myButton {
        // Get the reference to the current toolbar buttons
        NSMutableArray *navBarBtns = [self.navigationItem.rightBarButtonItems mutableCopy];
    
        // This is how you remove the button from the toolbar and animate it
        [navBarBtns removeObject:myButton];
        [self.navigationItem setRightBarButtonItems:navBarBtns animated:YES];
    }
    
    
    -(void) showBarButtonItem :(UIBarButtonItem *)myButton {
        // Get the reference to the current toolbar buttons
        NSMutableArray *navBarBtns = [self.navigationItem.rightBarButtonItems mutableCopy];
    
        // This is how you add the button to the toolbar and animate it
        if (![navBarBtns containsObject:myButton]) {
            [navBarBtns addObject:myButton];
            [self.navigationItem setRightBarButtonItems:navBarBtns animated:YES];
        }
    }
    

    When ever required use below Function..

    [self showBarButtonItem:self.rightBarBtn1];
    [self hideBarButtonItem:self.rightBarBtn1];
    

提交回复
热议问题