How do I show/hide a UIBarButtonItem?

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

    You need to manipulate the toolbar.items array.

    Here is some code I use to hide and display a Done button. If your button is on the extreme edge of the toolbar or in-between other buttons your other buttons will move, so if you want your button to just disappear then place your button as the last button towards the centre. I animate the button move for effect, I quite like it.

    -(void)initLibraryToolbar {
    
        libraryToolbarDocumentManagementEnabled = [NSMutableArray   arrayWithCapacity:self.libraryToolbar.items.count];
        libraryToolbarDocumentManagementDisabled = [NSMutableArray arrayWithCapacity:self.libraryToolbar.items.count];
        [libraryToolbarDocumentManagementEnabled addObjectsFromArray:self.libraryToolbar.items];
        [libraryToolbarDocumentManagementDisabled addObjectsFromArray:self.libraryToolbar.items];
        trashCan = [libraryToolbarDocumentManagementDisabled objectAtIndex:3];
        mail = [libraryToolbarDocumentManagementDisabled objectAtIndex:5];
        [libraryToolbarDocumentManagementDisabled removeObjectAtIndex:1];
        trashCan.enabled = NO;
        mail.enabled = NO;
        [self.libraryToolbar setItems:libraryToolbarDocumentManagementDisabled animated:NO];
    

    }

    so now can use the following code to show your button

    [self.libraryToolbar setItems:libraryToolbarDocumentManagementEnabled animated:YES];
    trashCan.enabled = YES;
    mail.enabled = YES; 
    

    or to hide your button

    [self.libraryToolbar setItems:libraryToolbarDocumentManagementDisabled animated:YES];
    trashCan.enabled = NO;
    mail.enabled = NO;
    

提交回复
热议问题