Question

I'm trying to add swipe detection on a 2 table cells. However, so far the swipe detection only works with one table cell.

Here are parts of my code:

- (void)viewDidLoad {

     [super viewDidLoad];
     numbers = [[NSMutableArray alloc]init];
     tableCellTrash = [[NSMutableArray alloc]init];

     mSwipeRecognizer= [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(removeCell:)];
     [mSwipeRecognizer setDirection:( UISwipeGestureRecognizerDirectionLeft | UISwipeGestureRecognizerDirectionRight)];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"CustomPlaceCell";
    CustomPlaceCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"CustomPlaceCell" owner:nil options:nil] objectAtIndex:0];
        [numbers addObject:cell];
        [cell addGestureRecognizer:mSwipeRecognizer];
        NSLog(@"Cell");
    }

    return cell;
}

-(void)removeCell:(UISwipeGestureRecognizer *)aSwipeGestureRecognizer{
    NSLog(@"Swipe Detected!");
}

Anyone know why swipe detection only works for one of cells?

Was it helpful?

Solution

A UIGestureRecognizer can be associated only ton a single view. You should set a different gestureRecognizer for each of your cells. You may move the GestureRecognizer creation inside the

     if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"CustomPlaceCell" owner:nil options:nil] objectAtIndex:0];
        [numbers addObject:cell];

        UISwipeGestureRecognizer *swipeRecognizer= [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(removeCell:)];
        [swipeRecognizer setDirection:( UISwipeGestureRecognizerDirectionLeft | UISwipeGestureRecognizerDirectionRight)];     

        [cell addGestureRecognizer:swipeRecognizer];

        NSLog(@"Cell");
    }

OTHER TIPS

You'd better add gesture in CustomPlaceCell's method:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier.

Also, you'd better do:

[cell.contentView addGestureRecognizer:]

, instead of cell itself. You'll find a lot of benefits if you do more complicate behavior in reusable cells.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top