endo.anaconda
endo.anaconda

Reputation: 2468

change image of UIBarButton

My target is to change the Image of an UIBarButton (which i use as IBOutlet) programmatically.

I found this solution on stackoverflow change-image-of-uibutton-with-other-image. but this is not working on iOS 4.2.

Can anyone help me with that. Simon

I tried:

UIImage *image = [UIImage imageWithContentsOfFile: 
                 [[NSBundle mainBundle] pathForResource:@"play" ofType:@"png"]];
playButton.image = image;

UIImage *image = [UIImage imageWithContentsOfFile:
                 [[NSBundle mainBundle] pathForResource:@"play" ofType:@"png"]];UIImage *image = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"play" ofType:@"png"]];
CGRect frame = CGRectMake(0, 0, image.size.width, image.size.height);
UIButton* someButton = [[UIButton alloc] initWithFrame:frame];
[someButton setBackgroundImage:image forState:UIControlStateNormal];
[someButton setShowsTouchWhenHighlighted:YES];
playButton = [[UIBarButtonItem alloc]initWithCustomView:someButton];

[someButton release];

Upvotes: 3

Views: 2897

Answers (1)

Satya
Satya

Reputation: 3330

If you want to put an image to a button use following code.

UIImage *image = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"play" ofType:@"png"]];

CGRect frame = CGRectMake(0, 0, image.size.width, image.size.height);

UIButton* someButton = [UIButton buttonWithType:UIButtonTypeCustom];
[someButton setBackgroundImage:image forState:UIControlStateNormal];
[someButton setShowsTouchWhenHighlighted:YES];
playButton = [[UIBarButtonItem alloc]initWithCustomView:someButton];

Upvotes: 6

Related Questions