UICollectionView:将单个Tap Gesture Recognizer添加到补充视图

con*_*xyz 11 objective-c uigesturerecognizer uicollectionview

我有一个带有补充视图的UICollectionView - 本质上是集合的标题.每当我使用界面构建器向headerView.xib中的UILabel添加手势识别器时,应用程序崩溃给我

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'invalid nib registered for identifier (MY_HEADER) - nib must contain exactly one top level object which must be a UICollectionReusableView instance'
Run Code Online (Sandbox Code Playgroud)

是什么阻止我在UICollectionView的补充视图中向UILabel添加手势识别器?

con*_*xyz 20

因此,您似乎无法使用界面构建器将手势识别器添加到UICollectionView的补充视图中.

我相信这是因为当加载.xib时,UICollectionView必须作为一个东西出现在超级视图中 - 当你将手势识别器添加到UICollectionView时,你最终会在超级视图级别有两个东西,它们都对应于UICollectionView.

但是,您可以使用UICollectionViewReusableView协议内部补充视图的定义以编程方式实现手势识别器.(if用于区分代码中稍后的标题补充视图和页脚补充视图)

if (kind == UICollectionElementKindSectionHeader) {
    MyHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MY_HEADER" forIndexPath:indexPath];

    // call headerView methods (to put things into the header's UI objects for example)
    [headerView ...];
    [headerView ...];
    [headerView ...];

    // add gesture recognition for tapping on a UIlabel within the header (UICollectionView supplementary view)
    UITapGestureRecognizer *bioTap = [[UITapGestureRecognizer alloc] initWithTarget:headerView action:@selector(handleUILabelTap:)];
    // make your gesture recognizer priority
    bioTap.delaysTouchesBegan = YES;
    bioTap.numberOfTapsRequired = 1;
    [headerView.UILabelName addGestureRecognizer:UILabelTap];

    reusableview = headerView;
}
Run Code Online (Sandbox Code Playgroud)