3

viewForSupplementaryElementOfKind からこの「空の配列の境界を超えたインデックス 0」エラーが発生することがあります。通常、コレクションは正常にロードされ、すべてがスムーズに実行されます。どの配列が空なのだろうか?登録された細胞?(コードまたはインターフェイスビルダーから登録しようとしましたが、まだ変更されていません)

コレクションの読み込みの早い段階でこのメソッドが呼び出され、まだ読み込まれていないデータが不足している場合があると推測しています。

誰かが私を任意の方向に向けることができますか?

私の実装は非常に簡単です:(そして、ビューで適切な再利用識別子を使用しました)

- (UICollectionReusableView *)collectionView:(UICollectionView *)theCollectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)theIndexPath{
UICollectionReusableView *theView;

if(kind == UICollectionElementKindSectionHeader)
{
    theView = [theCollectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:theIndexPath];
} else {
    theView = [theCollectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer" forIndexPath:theIndexPath];
}

return theView;}
4

2 に答える 2

1

このクラッシュで長い間遊んだ後、次のことがわかりました。

  • フロー レイアウトで Nib ファイルのセクション ヘッダー サイズをゼロ以外に設定して Nib からコレクション ビューをロードすると、クラッシュします。

  • Nib ファイルでフロー レイアウトのセクション ヘッダーのサイズをゼロに設定し、viewDidLoad で適切に設定すると、クラッシュしません。

    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        [self.collectionView registerNib:[UINib nibWithNibName:@"HeaderView" bundle:nil]
            forSupplementaryViewOfKind:UICollectionElementKindSectionHeader
            withReuseIdentifier:sHeaderViewIdentifier];
    
        [self.collectionView registerNib:[UINib nibWithNibName:@"Cell" bundle:nil] forCellWithReuseIdentifier:sCellIdentifier];
    
        UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
        layout.headerReferenceSize = CGSizeMake(self.collectionView.bounds.size.width, 50.f);
        [layout invalidateLayout];
    }
    
于 2014-05-02T20:21:25.893 に答える
-2

これが時々クラッシュする理由はまだわかりませんが、このコードを try-catch ブロックでラップし、ビューをデキューする代わりにビューを割り当てると、コレクションは正常にロードされ続けるようです..

if(kind == UICollectionElementKindSectionHeader) {
   theView = [theCollectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:theIndexPath];
} 

になる :

if(kind == UICollectionElementKindSectionHeader)
{
    @try {
        theView = [theCollectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:theIndexPath];
    }
    @catch (NSException * e) {
        NSLog(@"Exception: %@", e);
        theView = [[UICollectionReusableView alloc] init];
    }
    @finally {
        return theView;
    }

} 

UICollectionReusableView を割り当てるのは良い考えではないことはわかっていますが、今のところ、または実際の問題が見つかるまでは簡単に修正できます。

于 2013-11-07T09:28:02.143 に答える