How do I show/hide a UIBarButtonItem?

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

    self.dismissButton.customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];

    0 讨论(0)
  • 2020-11-28 01:50

    I know this answer is late for this question. However, it might help if anybody else faces a similar situation.

    In iOS 7, to hide a bar button item, we can use the following two techniques :-

    • use SetTitleTextAttributes :- This works great on bar button items like "Done", "Save" etc. However, it does not work on items like Add, Trash symbol etc.(atleast not for me) since they are not texts.
    • use TintColor :- If I have a bar button item called "deleteButton" :-

    To hide the button, I used the following code:-

    [self.deleteButton setEnabled:NO]; 
    [self.deleteButton setTintColor: [UIColor clearColor]];
    

    To show the button again I used the following code:-

    [self.deleteButton setEnabled:YES];
    [self.deleteButton setTintColor:nil];
    
    0 讨论(0)
  • 2020-11-28 01:50

    I used IBOutlets in my project. So my solution was:

    @IBOutlet weak var addBarButton: UIBarButtonItem!
    
    addBarButton.enabled = false
    addBarButton.tintColor = UIColor.clearColor()
    

    And when you'll need to show this bar again, just set reversed properties.

    In Swift 3 instead enable use isEnable property.

    0 讨论(0)
  • 2020-11-28 01:50

    If you are using Swift 3

    if (ShowCondition){
       self.navigationItem.rightBarButtonItem = self.addAsset_btn 
     } 
    else {
       self.navigationItem.rightBarButtonItem = nil
     }
    
    0 讨论(0)
  • 2020-11-28 01:51

    Just Set barButton.customView = UIView() and see the Trick

    0 讨论(0)
  • 2020-11-28 01:55

    This is long way down the answer list, but just in case somebody wants an easy copy and paste for the swift solution, here it is

    func hideToolbarItem(button: UIBarButtonItem, withToolbar toolbar: UIToolbar) {
        var toolbarButtons: [UIBarButtonItem] = toolbar.items!
        toolbarButtons.removeAtIndex(toolbarButtons.indexOf(button)!)
        toolbar.setItems(toolbarButtons, animated: true)
    }
    
    func showToolbarItem(button: UIBarButtonItem, inToolbar toolbar: UIToolbar, atIndex index: Int) {
        var toolbarButtons: [UIBarButtonItem] = toolbar.items!
        if !toolbarButtons.contains(button) {
            toolbarButtons.insert(button, atIndex: index)
            toolbar.setItems(toolbarButtons, animated:true);
        }
    }
    
    0 讨论(0)
提交回复
热议问题