change image of uibutton with other image
This way i have created my custom button and set the image.I have set the image for nonselectedImage and selectedImage above in load view.When the view is loaded the nonselected image is visible. When i press the button the event is called but it is not able to change the image set in the action metho开发者_运维百科d.
starImageBtn5 = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
starImageBtn5.frame = CGRectMake(231.0, 67.0, 20.0, 20.0);
[starImageBtn5 setBackgroundImage:nonSelectedImage forState:UIControlStateNormal];
[cell.contentView addSubview:starImageBtn5];
[starImageBtn5 addTarget:self action:@selector(actionForStar5) forControlEvents:UIControlEventTouchUpInside];
[starImageBtn5 release];
This is the method where i am trying to change the image.The starOneSelected is a bool variable.
- (void) actionForStar1
{
if(starOneSelected)
{
UIImage *image =[UIImage imageNamed:@"star-selected.png"] ;
// [UIImage imageNamed:@"star-nonselected.png"];
[starImageBtn1 setBackgroundImage:image forState:UIControlStateNormal];
//starImageBtn1.currentBackgroundImage= image;
starOneSelected = FALSE;
}
else
{
//[nonSelectedImage release];
[starImageBtn1 setBackgroundImage:selectedImage forState:UIControlStateNormal];
//UIButton *test = starImageBtn1.
starOneSelected = TRUE;
}
}
Please look at the code and try to help me out.i have gone through all the questions posted in this forum as well as other forums but not able to know where i am going wrong. Thanks in advance.
Instead of changing the image in your actionForStar1 method, do it when you create your button:
[starImageBtn5 setBackgroundImage:nonSelectedImage forState:UIControlStateNormal];
[starImageBtn5 setBackgroundImage:selectedImage forState:UIControlStateSelected];
精彩评论