我有一个带有补充视图的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'
是什么阻止我在UICollectionView的补充视图中向UILabel添加手势识别器?
因此,您似乎无法使用界面构建器将手势识别器添加到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;
}
我也无法通过IB向手机添加手势。
但是,我的经验是使用IB,您可以通过将一个手势识别器拖到outlineView中的collectionView项而不是在图形表示中位于collectionView顶部的scrollView,将其添加到collectionView本身。
到目前为止,我只能通过单元格进入collectionView。
当从笔尖加载补充视图时,我添加了手势识别器。
class MySuppleMentaryView: UICollectionReusableView
{
@IBOutlet var label: UILabel!
weak var delegate: MySuppleMentaryViewDelegate!
override func awakeFromNib() {
super.awakeFromNib()
// NOTE: UILabel MUST enable user interaction to receive touch events.
// label.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(onClickLabel))
tap.delaysTouchesBegan = true
tap.numberOfTapsRequired = 1
self.label.addGestureRecognizer(tap)
}
@objc func onClickLabel() {
self.delegate.didOnLabel(cell: self)
}
}
protocol MySuppleMentaryViewDelegate: NSObjectProtocol {
func didOnLabel(cell: DCScheduleHourLabel)
}
// Configure supplementary cell
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if (kind == UICollectionElementKindSectionHeader) {
// NOTE: The cell might be reused.
// If gesture recognizer is added HERE,
// then maybe multiple gesture recognizers are added when reusing the cell.
let cell = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: DCScheduleDummyBlock.Identifier, for: indexPath) as! MySuppleMentaryView
// configure cell
cell.delegate = self
return cell
}
return UICollectionReusableView()
}
如何在nib加载后以编程方式添加它?或者,在IB中,您尝试移动代表识别器的图标的位置,该位置代表视图的上方或下方