将UICollectionView触摸事件传递给其父UITableViewCell

tou*_*bun 10 uitableview ios uicollectionview

这是视图结构:

外观是一个UITableView.

在里面UITableViewCell,有一个UICollectionView.请注意,集合视图单元格之间存在一些黑色间距.

当我点击UICollectionView中的间距时,我希望触摸事件传递给UITableViewCell.

截图

Wil*_* T. 11

@tounaobun的优秀答案.经过测试,它按预期工作:

1)如果您点击集合视图中不是项目的任何位置,则下面的表格单元格将选择正常.

2)如果你点击集合视图中的项目,那么表格单元格将不会选择,你可以正常地与集合视图交互(也就是说,滚动,调用didSelectItem等)

我转换为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
    }

}
Run Code Online (Sandbox Code Playgroud)

只需将此类定义添加到您的代码中(我将它放在实用程序文件中),然后将集合视图的类从UICollectionView更改为TableCellCollectionView,您应该全部设置.


tou*_*bun 6

在google之后,我找到了一个解决方案.只需继承UICollectionViewclass和override hitTest:withEvent方法.

CustomCollectionView.h

@interface CustomCollectionView : UICollectionView

@end
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)