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

时间:2013-06-05 15:10:12

标签: ios uiscrollview uigesturerecognizer uicollectionviewcell touch-event

我有一个自定义UICollectionViewCell子类,其中包含UIScrollView

滚动视图正确滚动,但它会拦截点按,因此集合视图单元格突出显示和选择无法按预期工作。

userInteractionEnabled设置为NO可以点击“直通”,但滚动不起作用(当然)。

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

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

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

将UITapGestureRecognizer添加到滚动视图。

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(scrollViewTapped:)];
[scrollView addGestureRecognizer:tapGesture];

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

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