Tuesday, August 31, 2010

Custom accessory view of table view cell : accessoryButtonTappedForRowWithIndexPath method is not called

In my attempt to implement a custom accessory view for table view cell, I faced a weird problem. While everything in my code looked okay, the accessoryButtonTappedForRowWithIndexPath method was not being invoked when I tapped the custom accessory button.

Sample code Accessory provided by Apple helped me sort out the problem. Here the clue is that the custom accessory view must have a custom button which will be wired to a predetermined target and action.

In the method cellForRowAtIndexPath:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
// match the button's size with the image size
button.frame = frame;
[button setBackgroundImage:image forState:UIControlStateNormal];


// set the button's target to this table view controller so
// we can interpret touch events and map that to a NSIndexSet

[button addTarget:self action:@selector(checkButtonTapped:event:) forControlEvents:UIControlEventTouchUpInside];

cell.accessoryView = button;



- (void)checkButtonTapped:(id)sender event:(id)event
{
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
if (indexPath != nil)
{
[self tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
}
}


Reference:
Sample code of custom accessory view from Apple

No comments:

Post a Comment