将补充标题视图添加到UICollectionView时出错

时间:2013-08-09 03:38:43

标签: objective-c uicollectionview ios7 xcode5 uicollectionreusableview

我在实现补充标题视图

时遇到以下错误
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'no UICollectionViewLayoutAttributes instance for -layoutAttributesForSupplementaryElementOfKind: HeaderView at path <NSIndexPath: 0x9e82a40> {length = 2, path = 0 - 0}'

这是创建标题视图的代码

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    static NSString * headerIdentifier = @"HeaderView";
    UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:headerIdentifier withReuseIdentifier:UICollectionElementKindSectionHeader forIndexPath:indexPath];
    return header;
}

在dequeueReusableSupplementaryViewOfKind方法中发生错误。

我在Collection View Controller的initWithCoder中添加了这两行

UINib *headerNib = [UINib nibWithNibName:@"MTCollectionHeaderView" bundle:nil];
[self.collectionView registerNib:headerNib forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"];

所以它确实有对UI元素的引用。无论如何我都找不到在标题上设置布局。

我尝试将其添加到同一个集合视图控制器中,但它从未点击此代码,因为我通过调试器确认

- (UICollectionViewLayoutAttributes *)layoutAttributesForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    return [self.collectionViewLayout layoutAttributesForDecorationViewOfKind:kind atIndexPath:indexPath];
}

有没有人见过这个问题,他们是如何解决的。我也在使用XCode 5 Developer Preview 5并开发iOS7

1 个答案:

答案 0 :(得分:6)

我相信你传递的是headerIdentifier,用于补充视图的种类和头标识符的种类常量。尝试按照collectionView:viewForSupplementaryElementOfKind:atIndexPath:方法中的以下代码行显示切换它们:

UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerIdentifier forIndexPath:indexPath];

我也认为你不需要实现layoutAttributesForSupplementaryElementOfKind:atIndexPath:,交换上面的代码行,看看它是否有效。