3

下面是相關的代碼:無法獲得UICollectionView頭工作

控制器:

- (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>>) 

我調試,並確保它不返回零。所以我覺得它的registerClass部分工作不正常。我將不勝感激任何意見。謝謝。

回答

4

一個明確的問題是在這裏:

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

該代碼是沒有意義的。在第一行中,您將標題視圖出列。在第二行中,您只是丟棄剛剛出列的標題視圖並創建一個全新的標題視圖。

+0

你說得對。那是愚蠢的。謝謝。 – isal

+0

但是我從來沒有見過這個特殊的例外,所以瞭解它很有趣!因此你的問題是一個很好的問題。畢竟,別人可能會遇到同樣的例外。 – matt