无法更改UIBarButtonItem图像

时间:2010-11-22 14:41:04

标签: iphone objective-c ios uibarbuttonitem

我正在尝试各种方法来更改UIBarButtonItem的图像,一旦按下它,没有任何运气。

// 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"];
}

还有其他办法吗?

4 个答案:

答案 0 :(得分:2)

工具栏包含一个数组 - 项目 - 作为属性。因此,在将工具栏设置为IBOutlet属性后,我不得不在该数组中插入一个新按钮..就像这样:

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

答案 1 :(得分:0)

bookmarkButton是UIButton吗?它应该通过(UIButton *)aBarButtonItem.customView而不是直接引用吗?

如果是UIButton,那么您需要根据状态设置图像:- (void)setImage:(UIImage *)image forState:(UIControlState)state

请注意,如果您需要,还有setBackgroundImage具有相同的API。

答案 2 :(得分:0)

这应该有效

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;

答案 3 :(得分:-3)

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