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

Monday, August 30, 2010

Warning : declaration of 'variableName' hides instance variable

The large number of warnings of the following kind seem to me really annoying, though I can realize the need of it.

declaration of 'variableName' hides instance variable

I googled for a nice work-around to avoid this warning but could not find any. Many have suggested to use underscore prefix for instance variables but some pointed out that underscore prefix notation has been reserved by Apple. The others suggested to use the convention of using the/a/an before the variable name but it seems to me quite distasteful!

Helpless, I opted for the latter solution :-(

References:
1. Objective-C convention to prevent “local declaration hides instance variable” warning
2. Suppressing variable hiding warning in Xcode
3. Parameters hide instance variables in Objective-C