I am having difficulty in changing the image of my UIButton which is contained within a table view cell. My code as follows:
// In tableview for cell at rowIndex method
self.iconBtn = [[UIButton alloc]initWithFrame:CGRectMake(670,10,80, 80)];
self.iconBtn.tag = kIconValueTag;
[cell.contentView addSubview:self.iconBtn];
//Add icon to cell
UIImage *btnImage = [UIImage imageNamed:@"blank_star.png"];
[self.iconBtn setImage:btnImage forState:UIControlStateNormal];
// I am calling method changeIconState after user clicks on icon.
[self.iconBtn addTarget:self action:@selector(changeIconState) forControlEvents:UIControlEventTouchUpInside];
After the button is pressed, a method outside the table view method is called:
-(void)changeIconState
{
if (self.iconSelectState == kIconNotSelected)
{
self.iconSelectState = kIconSelected;
}
else
{
self.iconSelectState = kIconNotSelected;
}
[self changeIcon];
}
-(void)changeIcon
{
if (self.iconSelectState == kIconSelected)
{
UIImage *btnImageHighlighted = [UIImage imageNamed:@"star.png"];
[self.iconBtn setImage:btnImageHighlighted forState:UIControlStateNormal];
}
else
{
UIImage *btnImageNormal = [UIImage imageNamed:@"blank_star.png"];
[self.iconBtn setImage:btnImageNormal forState:UIControlStateNormal];
}
}
After I run the program, the icon did not change from blank to star as I wanted. It just remained as a blank star. Is there anything I am missing out here?
Why are you managing the image/button state yourself? Why not load the two images for the defined states and let the OS handle it?
If you need to manage your property (iconSelectedState) you can without worrying about the image. Alternatively, you can query the buttons state property to determine which state it is in.