Search code examples
objective-cioseventsuibarbuttonitemuitoolbar

How to get current index of UIBarButtonItem to remove it by clicking event?


I'm in the process of learning Objective-C and iOS development. So, I implemented removing of UIBarButtonItem from UIToolBar on UIControlEventTouchDown event in the selector. But this works really bad and the code is not very declarative as you see:

- (void)barButtonClicked:(id)sender
{
     NSArray * const itemsArray = userToolbar.items;
     NSMutableArray * mutableItems = [NSMutableArray arrayWithArray:itemsArray];
    [mutableItems removeObjectAtIndex:0];
    [userToolbar setItems: mutableItems animated:YES];
}

So as you see I removed item accordingly to its index in the userToolbar items array. It's not what I really want. I have on my UIToolBar nearly 10-12 UIBarItemButtons and I want define one common event for them all: removing it from the bar by clicking on it. So I need something like this:

[mutableItems removeObjectAtIndex:sender.currentIndexInToolBarItemsArray]

So, the question how can I implement this?


Solution

  • Instead of removing the object at the constant index 0, use the removeObject: method of NSMutableArray:

    [mutableItems removeObject:sender];