Ios 将UICollectionView触摸事件传递给其父UITableViewCell
以下是视图结构: 外部视图是一个Ios 将UICollectionView触摸事件传递给其父UITableViewCell,ios,uitableview,uicollectionview,Ios,Uitableview,Uicollectionview,以下是视图结构: 外部视图是一个UITableView 在UITableViewCell中,有一个UICollectionView。请注意,集合视图单元格之间有一些黑色间距 在UICollectionView中点击间距时,我希望触摸事件传递到UITableViewCell 在谷歌搜索之后,我找到了一个解决方案。只需继承UICollectionView类并重写hitTest:withEvent方法 CustomCollectionView.h @interface CustomCollection
UITableView
在UITableViewCell
中,有一个UICollectionView
。请注意,集合视图单元格之间有一些黑色间距
在UICollectionView中点击间距时,我希望触摸事件传递到UITableViewCell
在谷歌搜索之后,我找到了一个解决方案。只需继承
UICollectionView
类并重写hitTest:withEvent
方法
CustomCollectionView.h
@interface CustomCollectionView : UICollectionView
@end
CustomCollectionView.m
@implementation CustomCollectionView
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
UIView *hitView = [super hitTest:point withEvent:event];
if ([hitView isKindOfClass:[self class]]) {
// If it is class UICollectionView,just return nil.
return nil;
}
// else return super implementation.
return [super hitTest:point withEvent:event];
}
@end
是否可以设置collectionView的backgroundView UserInteraction不启用,但请确保collectionViewCell启用,以便它可以将TapeEvent传递给下一个响应程序
- (void)viewDidLoad {
theCollectionView.userInteractionEnabled = NO;
}
我希望这会有所帮助。@tounaobun的回答非常好。经过测试,工作正常: 1) 如果点击集合视图中非项目的任何位置,则下面的表格单元格将选择“刚刚好” 2) 如果点击集合视图中的项目,则表格单元格将不会选择,您可以正常与集合视图交互(也称为滚动、调用didSelectItem等) 我转换成swift以供参考: Swift 3:
class TableCellCollectionView: UICollectionView {
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if let hitView = super.hitTest(point, with: event) {
if hitView is TableCellCollectionView {
return nil
} else {
return hitView
}
} else {
return nil
}
}
只需将此类定义添加到代码中(我在实用程序文件中有它),然后将集合视图的类从UICollectionView更改为TableCellCollectionView,您就可以完成所有设置。投票率最高的答案中的代码可以很容易地缩短 Swift 4.1:
final class InteractiveCollectionView: UICollectionView {
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
return super.hitTest(point, with: event) as? InteractiveCollectionView
}
}
您可以覆盖
UICollectionView
的点(内部:with:)
方法,并手动检查是否有任何单元格包含指定点:
class CollectionView: UICollectionView {
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
visibleCells.contains(where: { $0.frame.contains(point) })
}
}
这样UICollectionViewCell就无法响应用户交互。我有一个类似的情况:UICollectionViewCell位于另一个UICollectionViewCell中。但是,我只能从包含另一个单元格的单元格中检测到点击(通过didSelectItem委托方法)。但我需要探测到里面牢房的窃听声。这不起作用。@vikzilla你找到解决办法了吗?我也有同样的问题。这种简化是错误的,当点击CollectionView时应该返回nil。但是,此代码将返回找到的CollectionView,因此不允许父级处理该点击。