【问题标题】:UIScrollView as subview of UICollectionViewCell - passing tap to superviewUIScrollView 作为 UICollectionViewCell 的子视图 - 将点击传递给超级视图
【发布时间】:2013-06-01 08:44:03
【问题描述】:
我有一个自定义的 UICollectionViewCell 子类,其中包含一个 UIScrollView。
滚动视图可以正确滚动,但是它会拦截点击,因此集合视图单元格突出显示和选择无法按预期工作。
将userInteractionEnabled 设置为NO 允许点击“通过”但滚动不起作用(当然)。
覆盖hitTest:withEvent: 是没有用的,因为我需要在转发之前知道它是点击还是平移。
有什么想法吗?
【问题讨论】:
标签:
ios
uiscrollview
uigesturerecognizer
uicollectionviewcell
touch-event
【解决方案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];
}
}
}
}
}