0

I found already some solution how to detect touch in my cell, but they are made for one section. I have more then 1(8 tbh). Following code are making touch for few cells instead of one. So question is, what the clear solution to my problem? Here the code:

- (CatalogItemTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CatalogItemTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

CatalogItemModel *currentItemModel;

if(isCatSelected) {
    currentItemModel = [[self.itemsArray objectForKey:[[self.sectionArray objectAtIndex:selectedIndexPath] valueForKey:@"id"]] objectAtIndex:indexPath.row];
} else {
    currentItemModel = [[self.itemsArray objectForKey:[[self.sectionArray objectAtIndex:indexPath.section] valueForKey:@"id"]] objectAtIndex:indexPath.row];
}

[cell setItemModel:currentItemModel];

UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                    action:@selector(didTapFav:)];
[cell.overFavorite addGestureRecognizer:gestureRecognizer]; //overFavorite is UIView to detect touch

return cell;
}

Action func:

-(void)didTapFav:(UITapGestureRecognizer*)recognizer {
NSString *token = [ProfileManager getToken];
if(token.length > 0){
    [[NSNotificationCenter defaultCenter] postNotificationName:@"addToFavorite" object:self];
} else {
    [self showErrorWithTitle:@"Auth" andText:@"To add item in Favorite!"];
}

}

Function inside CatalogItemTableViewCell:

-(void)addToFavorite {
    if(isFavorite) {
        [ApiManager tryAddToFavItem:[NSString stringWithFormat:@"%ld", (long)self.currentModel.uid] :^{
            //Some API request
        }];
    }
}
Ilya Chikmarev
  • 133
  • 1
  • 11
  • Use a delegation pattern or a closure. See [these answers](https://stackoverflow.com/questions/28659845/swift-how-to-get-the-indexpath-row-when-a-button-in-a-cell-is-tapped/38941510#38941510) – Paulw11 Dec 27 '17 at 23:24
  • Give the target view a tag. – El Tomato Dec 27 '17 at 23:43
  • @ElTomato don’t use tags to represent index paths. It fails if rows can be inserted, deleted, or moved. – rmaddy Dec 28 '17 at 00:26

1 Answers1

0

First of all add gestureRecognizer for your CollectionView

UIGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)]; tapGesture.delegate = self; [self.collectionView addGestureRecognizer:tapGesture];

then get the IndexPath or Cell you want to access in - (void)tap:(UITapGestureRecognizer* )sender;

if (sender.state == UIGestureRecognizerStateEnded) {

    NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[sender locationInView:self.collectionView]];
}