Question

I have a favorite image to display on a UIBarButtonItem, on an toolbar.

How do you do to change it when this item is unselected/selected? like this screenshot:

enter image description here

Thanks!

Was it helpful?

Solution

You can make two arrays with UIBarButtonItems: one with the first image and one with the second image. Like this:

// array with unselected
UIBarButtonItem *unselectedItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_unselected.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(doStuff:)];
self.itemsWithUnselected = [NSArray arrayWithObject:unselectedItem]; // declared as NSArray*
[unselectedItem release];

// array with selected
UIBarButtonItem *selectedItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_selected.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(doStuff:)];
self.itemsWithSelected = [NSArray arrayWithObject:selectedItem]; // declared as NSArray*
[selectedItem release];

and then switch between the two sets of toolbar items with:

toolbar.items = self.itemsWithSelected; // or self.itemsWithUnselected

If you have more than just the one button on your toolbar then just add the rest of the items to both arrays.

OTHER TIPS

// First create UIButton object
UIButton *btnCustom = [UIButton buttonWithType:UIButtonTypeCustom];

// Set Frame because without frame your button can not be shown on navigation bar
[btnCustom setFrame:CGRectMake(0.0, 0.0, 20.0, 20.0)];

// Set unselected image
[btnCustom setImage:[UIImage imageNamed:@"YOUR_IMAGE_NAME_UNSELECTED"] forState:UIControlStateNormal];

// set selected image
[btnCustom setImage:[UIImage imageNamed:@"YOUR_IMAGE_NAME_SELECTED"] forState:UIControlStateSelected];

// set action method
[btnCustom addTarget:self action:@selector(btnCustom_click:) forControlEvents:UIControlEventTouchUpInside];


UIBarButtonItem *btnCustomBar = [[UIBarButtonItem alloc]initWithCustomView:btnCustom];

[self.navigationItem setRightBarButtonItem:btnCustomBar];

// action Method

- (IBAction)btnCustom_click:(id)sender
{
   if(![sender isSelected])
       [sender setSelected:YES];
   else
       [sender setSelected:NO];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top