I have a UITableview
that I'm displaying some tasks and each row has a checkbox to mark tasks complete or not.
I'm looking to toggle the checkmark when the user taps on the checkbox, and switch to a detailed view when the user taps on the row. The latter is easy, just by using
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
However, I wanted to separate the selection areas, toggling only the checkbox when the accessoryview
is selected, and going into detailed view only when the rest of the cell is selected. If I add a UIbutton
inside the accessoryview
, the user would be selecting the row AND the UIButton
when they only wanted to hit the checkbox, right?
Also, what if the user was just scrolling through the tableview by dragging along the accessoryview
? Wouldn't this trigger an action on the UIButton
on TouchUp?
Anyone have any ideas on how to do this? Thanks for your time!
How about managing accessory taps inside this delegate method:
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
EDIT:
You can do something like this for custom accessoryView that responds to accessoryButtonTappedForRowWithIndexPath:
method.
In cellForRowAtIndexPath:
Method -
BOOL checked = [[item objectForKey:@"checked"] boolValue];
UIImage *image = (checked) ? [UIImage imageNamed:@"checked.png"] : [UIImage imageNamed:@"unchecked.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
button.frame = frame;
[button setBackgroundImage:image forState:UIControlStateNormal];
[button addTarget:self action:@selector(checkButtonTapped:event:) forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor = [UIColor clearColor];
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];
}
}
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
NSMutableDictionary *item = [dataArray objectAtIndex:indexPath.row];
BOOL checked = [[item objectForKey:@"checked"] boolValue];
[item setObject:[NSNumber numberWithBool:!checked] forKey:@"checked"];
UITableViewCell *cell = [item objectForKey:@"cell"];
UIButton *button = (UIButton *)cell.accessoryView;
UIImage *newImage = (checked) ? [UIImage imageNamed:@"unchecked.png"] : [UIImage imageNamed:@"checked.png"];
[button setBackgroundImage:newImage forState:UIControlStateNormal];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With