Custom UITableViewCell with UIButton: unable to change UIImage
ios, iphone, uibutton, uitableview
Solution
Try to modify your `AddToFav:` method to:
-(IBAction)AddToFav:(UIButton *)sender{
NSLog(@"Value of selected button = %ld",(long)[sender tag]);
[sender setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
[sender setBackgroundImage:[UIImage imageNamed:@"grey-star.png"] forState:UIControlStateNormal];
}
Or use this:
-(IBAction)AddToFav:(UIButton *)sender{
NSLog(@"Value of selected button = %ld",(long)[sender tag]);
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
for (UIButton *btn in [cell.contentView.superview subviews] ) {
if ([btn isKindOfClass:[UIButton class]]&& btn.tag ==(long)[sender tag]) {
[btn setBackgroundImage:[UIImage imageNamed:@"grey-star.png"]
}
}
}
Problem
I have a custom `UITableView` with custom `UITableViewCell` it contains an `UIButton` i want to change Background image of selected button when the user selects it, Unfortunately, the image is not changing state whenever I press it and it shows: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView setBackgroundImage:forState:]: Here is my code snippet: ``` - (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath { static NSString *CellIdentifier = @"BTSTicketsCellIdentifier"; CRIndCategCell *cell = (CRIndCategCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { //Initialize cell } cell.favBtn.tag=indexPath.row; [cell.favBtn addTarget:self action:@selector(AddToFav:) forControlEvents:UIControlEventTouchUpInside]; ... ... ... } -(IBAction)AddToFav:(id)sender{ NSLog(@"Value of selected button = %ld",(long)[sender tag]); UIButton *Btn=(UIButton*)[self.view viewWithTag:(long)[sender tag]]; [Btn setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal]; [Btn setBackgroundImage:[UIImage imageNamed:@"grey-star.png"] forState:UIControlStateNormal]; } ``` My Log shows Value of selected button correctly but unable to change image of button Thank you for reading.