【问题标题】:How to detect touches on UIView of UITableViewCell with more then one section?如何检测对 UITableViewCell 的 UIView 的触摸超过一个部分?
【发布时间】:2017-12-27 22:45:30
【问题描述】:

我已经找到了一些如何检测单元格中的触摸的解决方案,但它们是为一个部分制作的。我有超过 1 个(8 tbh)。以下代码正在触摸几个单元格而不是一个。所以问题是,我的问题的明确解决方案是什么?代码如下:

- (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;
}

动作函数:

-(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!"];
}

}

CatalogItemTableViewCell 内的函数:

-(void)addToFavorite {
    if(isFavorite) {
        [ApiManager tryAddToFavItem:[NSString stringWithFormat:@"%ld", (long)self.currentModel.uid] :^{
            //Some API request
        }];
    }
}

【问题讨论】:

  • 使用委托模式或闭包。见these answers
  • 给目标视图一个标签。
  • @ElTomato 不使用标签来表示索引路径。如果行可以插入、删除或移动,则失败。

标签: ios objective-c uitableview uiview


【解决方案1】:

首先为你的 CollectionView 添加gestureRecognizer

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

然后在-(void)tap:(UITapGestureRecognizer* )sender中获取你要访问的IndexPath或者Cell;

if (sender.state == UIGestureRecognizerStateEnded) {

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    相关资源
    最近更新 更多