How do I show/hide a UIBarButtonItem?

前端 未结 30 2154
执念已碎
执念已碎 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:01

    You can use text attributes to hide a bar button:

    barButton.enabled = false
    barButton.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.clearColor()], forState: .Normal)
    

    Also see my solution with UIBarButtonItem extension for the similar question: Make a UIBarButtonItem disapear using swift IOS

    0 讨论(0)
  • 2020-11-28 02:03

    There is no way to "hide" a UIBarButtonItem you must remove it from the superView and add it back when you want to display it again.

    0 讨论(0)
  • 2020-11-28 02:03

    One way to do it is use the initWithCustomView:(UIView *) property of when allocating the UIBarButtonItem. Subclass for UIView will have hide/unhide property.

    For example:

    1. Have a UIButton which you want to hide/unhide.

    2. Make the UIButtonas the custom view. Like :

    UIButton*myButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];//your button
    
    UIBarButtonItem*yourBarButton=[[UIBarButtonItem alloc] initWithCustomView:myButton];
    

    3. You can hide/unhide the myButton you've created. [myButton setHidden:YES];

    0 讨论(0)
  • 2020-11-28 02:04

    For Swift version, here is the code:

    For UINavigationBar:

    self.navigationItem.rightBarButtonItem = nil
    
    self.navigationItem.leftBarButtonItem = nil
    
    0 讨论(0)
  • 2020-11-28 02:05

    Save your button in a strong outlet (let's call it myButton) and do this to add/remove it:

    // Get the reference to the current toolbar buttons
    NSMutableArray *toolbarButtons = [self.toolbarItems mutableCopy];
    
    // This is how you remove the button from the toolbar and animate it
    [toolbarButtons removeObject:self.myButton];
    [self setToolbarItems:toolbarButtons animated:YES];
    
    // This is how you add the button to the toolbar and animate it
    if (![toolbarButtons containsObject:self.myButton]) {
        // The following line adds the object to the end of the array.  
        // If you want to add the button somewhere else, use the `insertObject:atIndex:` 
        // method instead of the `addObject` method.
        [toolbarButtons addObject:self.myButton];
        [self setToolbarItems:toolbarButtons animated:YES];
    }
    

    Because it is stored in the outlet, you will keep a reference to it even when it isn't on the toolbar.

    0 讨论(0)
  • 2020-11-28 02:06

    In case the UIBarButtonItem has an image instead of the text in it you can do this to hide it: navigationBar.topItem.rightBarButtonItem.customView.alpha = 0.0;

    0 讨论(0)
提交回复
热议问题