开发者

Having trouble changing a UIBarButtonItem's image

I'm trying various ways of changing a UIBarButtonItem's image once it has been pressed, without any 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 another way to do this?


The toolbar contains an array - items - as a property. So after setting up the toolbar as an IBOutlet property, I had to insert a new button into that array.. like this:

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];


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

If it is a UIButton then you'll want to set the image based on state: - (void)setImage:(UIImage *)image forState:(UIControlState)state

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


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;


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜