5

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

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

设置userInteractionEnabledNO允许点击“通过”但滚动不起作用(当然)。

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

有什么想法吗?

4

1 回答 1

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];
                }
            }
        }
    }
}
于 2014-03-07T22:51:55.163 回答