无法获取UICollectionView标头

时间:2014-03-29 21:20:23

标签: ios objective-c uicollectionview uicollectionreusableview

此处的相关代码:

控制器:

- (instancetype)init {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];

    layout.itemSize = CGSizeMake(106.0, 106.0);
    layout.minimumInteritemSpacing = 1.0;
    layout.minimumLineSpacing = 1.0;
    layout.headerReferenceSize = CGSizeMake(320.0, 44.0);

    return (self = [super initWithCollectionViewLayout:layout]);
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // some setup

    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;

    [self.collectionView registerClass:[ITPhotosHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];

}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    UICollectionReusableView *reusableView;

    if (kind == UICollectionElementKindSectionHeader) {
        ITPhotosHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                                                          withReuseIdentifier:@"header" forIndexPath:indexPath];
        headerView = [[ITPhotosHeaderView alloc] initWithFrame:CGRectMake(0, 0, 320.0, 44.0)];
        reusableView = headerView;
    }

    return reusableView;
}

这是我得到的错误:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'the view returned from -collectionView:viewForSupplementaryElementOfKind:atIndexPath (UICollectionElementKindSectionHeader,<NSIndexPath: 0xc000000000000016> {length = 2, path = 0 - 0}) was not retrieved by calling -dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath: or is nil (<ITPhotosHeaderView: 0x1781b9de0; baseClass = UICollectionReusableView; frame = (0 0; 320 44); layer = <CALayer: 0x17802f980>>)

我调试并确保它没有返回nil。因此我觉得registerClass部分无法正常工作。我很感激任何意见。感谢。

1 个答案:

答案 0 :(得分:5)

这里有一个明确的问题:

    ITPhotosHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                                                      withReuseIdentifier:@"header" forIndexPath:indexPath];
    headerView = [[ITPhotosHeaderView alloc] initWithFrame:CGRectMake(0, 0, 320.0, 44.0)];

该代码是荒谬的。在第一行中,您将标题视图出列。在第二行中,您只需要丢弃刚刚出列的标题视图并创建一个全新的标题视图。