UIScrollView作为UICollectionViewCell的子视图 - 将tap传递给superview

Ash*_*lls 5 uiscrollview touch-event uigesturerecognizer ios uicollectionviewcell

我有一个UICollectionViewCell包含a 的自定义子类UIScrollView.

滚动视图正确滚动,但是它会截取水龙头,因此集合视图单元格突出显示和选择无法按预期工作.

设置userInteractionEnabledNO使水龙头"通过",但滚动没有(当然)工作.

覆盖hitTest:withEvent:是没有用的,因为我需要知道它是转发之前的点击还是平移.

有什么想法吗?

Sco*_* K. 1

我今天遇到了这个。这是我解决问题的方法,但必须有更好的方法。我不必将集合视图选择逻辑放入我的单元格代码中。

将 UITapGestureRecognizer 添加到滚动视图。

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(scrollViewTapped:)];
[scrollView addGestureRecognizer:tapGesture];
Run Code Online (Sandbox Code Playgroud)

然后,在回调中,您必须模拟正常点击单元格时会发生什么:

-(void) scrollViewTapped:(UITapGestureRecognizer *)sender {
    UIView *tappedView = [sender view];

    while (![tappedView isKindOfClass:[UICollectionView class]]) {
        tappedView = [tappedView superview];
    }

    if (tappedView) {
        UICollectionView *collection = (UICollectionView *)tappedView;
        NSIndexPath *ourIndex = [collection indexPathForCell:self];
        BOOL isSelected = [[collection indexPathsForSelectedItems] containsObject:ourIndex];

        if (!isSelected) {
            BOOL shouldSelect = YES;
            if ([collection.delegate respondsToSelector:@selector(collectionView:shouldSelectItemAtIndexPath:)]) {
                shouldSelect = [collection.delegate collectionView:collection shouldSelectItemAtIndexPath:ourIndex];
            }

            if (shouldSelect) {
                [collection selectItemAtIndexPath:ourIndex animated:NO scrollPosition:UICollectionViewScrollPositionNone];
                if ([collection.delegate respondsToSelector:@selector(collectionView:didSelectItemAtIndexPath:)]) {
                    [collection.delegate collectionView:collection didSelectItemAtIndexPath:ourIndex];
                }
            }
        } else {
            BOOL shouldDeselect = YES;
            if ([collection.delegate respondsToSelector:@selector(collectionView:shouldDeselectItemAtIndexPath:)]) {
                shouldDeselect = [collection.delegate collectionView:collection shouldDeselectItemAtIndexPath:ourIndex];
            }

            if (shouldDeselect) {
                [collection deselectItemAtIndexPath:ourIndex animated:NO];
                if ([collection.delegate respondsToSelector:@selector(collectionView:didDeselectItemAtIndexPath:)]) {
                    [collection.delegate collectionView:collection didDeselectItemAtIndexPath:ourIndex];
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)