change image of uibutton with other image

烂漫一生 提交于 2019-12-13 06:31:59

问题


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 method.

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.


回答1:


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


来源:https://stackoverflow.com/questions/1547188/change-image-of-uibutton-with-other-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!