Failed to modify UIBarButtonItem image.

I am trying to use various ways to change the image of UIBarButtonItem when it was clicked, with no luck.

// bookmarkButton is a property linked up in IB -(IBAction)bookmarkButtonTapped:(id)sender { NSLog(@"this action triggers"); // attempt 1 UIBarButtonItem* aBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"bookmarkdelete.png"] style:UIBarButtonItemStylePlain target:self action:@selector(bookmarkButtonTapped:)]; bookmarkButton = aBarButtonItem; [aBarButtonItem release]; // attempt 2 bookmarkButton.image = [UIImage imageNamed:@"bookmarkdelete.png"]; } 

Is there any other way to do this?

+6
ios objective-c iphone uibarbuttonitem
source share
4 answers

The toolbar contains an array - elements - as a property. Therefore, after setting up the toolbar as an IBOutlet property, I had to insert a new button into this array. For example:

 NSMutableArray *items = [[NSMutableArray alloc] initWithArray:self.toolBar.items]; UIBarButtonItem *newButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"newButton.png"] style:UIBarButtonItemStylePlain target:self action:@selector(buttonTapped:)]; [items replaceObjectAtIndex:0 withObject:newButton]; self.toolBar.items = items; [newButton release]; [items release]; 
+2
source share

Is bookmarkButton a UIButton? Should it be referenced via (UIButton *)aBarButtonItem.customView instead of direct?

If it is a UIButton, you need to set the image based on state: - (void)setImage:(UIImage *)image forState:(UIControlState)state

Note that there is also setBackgroundImage with the same API if you want to.

0
source share

This should work

 UIImage *normalButtonImage = [UIImage imageNamed:@"TableViewIcon"]; UIImage *selectedButtonImage = [UIImage imageNamed:@"CollectionViewIcon"]; CGRect rightButtonFrame = CGRectMake(0, 0, normalButtonImage.size.width, normalButtonImage.size.height); UIButton *rightButton = [[UIButton alloc] initWithFrame:rightButtonFrame]; [rightButton setBackgroundImage:normalButtonImage forState:UIControlStateNormal]; [rightButton setBackgroundImage:selectedButtonImage forState:UIControlStateSelected]; [rightButton addTarget:self action:@selector(toggleTableView:) forControlEvents:UIControlEventTouchDown]; self.toggleMediaView = [[UIBarButtonItem alloc] initWithCustomView:rightButton]; [self.navigationItem setLeftBarButtonItem:self.toggleMediaView]; self.navigationItem.leftBarButtonItem.enabled = NO; 
0
source share

try [bookmarkButton setImage:[UIImage imageNamed:@"bookmarkdelete.png"] forState:UIControlStateNormal];

-3
source share

All Articles