syedfa syedfa - 20 days ago 4x
iOS Question

Unable to change button image when pressed inside a UITableViewCell in iOS application

I have a UITableViewController that contains a table, whose cells I wish to add a button to. This is a customized button that will act as a checkbox, with an image that it has for its normal state, and another image that it has when the user selects it. Unfortunately, the image is not changing state whenever I press it, and for some reason, it is also not calling the target method.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
static NSString *CellIdentifier = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone;

// Configure the cell...
TestObject *tObject = [myNSMutableArray objectAtIndex:indexPath.row];
cell.textLabel.text = tObject.testTitle;

testButton = [UIButton buttonWithType:UIButtonTypeCustom];
[testButton setFrame:CGRectMake(280, 57, 25, 25)];
[testButton setImage:[UIImage imageNamed:@"CheckBox1.png"] forState:UIControlStateSelected];
[testButton setImage:[UIImage imageNamed:@"CheckBox2.png"] forState:UIControlStateNormal];
[testButton setUserInteractionEnabled:YES];
[testButton addTarget:self action:@selector(clickOnCheckButton:) forControlEvents:UIControlEventTouchUpInside];

[cell addSubview:testButton];

return cell;


For the record, I have indeed implemented the method:

-(void)clickOnCheckButton:(id)sender {

NSLog(@"button has been pressed");

and have made sure the spelling is correct, which is why I don't understand the reason why the method is not being called when the button in each cell is pressed.

The other problem with my table output is that my very first cell does not have a button inside it. All other cells below it however, do.

Can anyone see what I am doing wrong?

Thanks in advance to all who reply.


If you use the cell's accessoryView property you can set it to a custom view, like your button, and it's designed to act like a button. You then have the option to use the UITableViewDelegate method – tableView:accessoryButtonTappedForRowWithIndexPath: to control the action.