2013-02-20 56 views
4

我有一个UICollectionView标题的尺寸非零。似乎每当insertItemsAtIndexPaths被调用,如果标题是在屏幕上,程序崩溃,并显示以下信息:IOS UICollectionView insertItemsAtIndexPaths在屏幕上显示标题时崩溃

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** setObjectForKey: object cannot be nil (key: <_UICollectionViewItemKey: 0xa38c910> Type = SV Kind = UICollectionElementKindSectionHeader IndexPath = <NSIndexPath 0xa38c7c0> 2 indexes [0, 0])' 

当头部大小是零,或者当标头不是在屏幕上,号召insertItemsAtIndexPaths工作正常。有谁知道如何解决这一问题?谢谢!

该类是UICollectionViewController的子类。下面是有关UICollectionView代码:

- (id)init { 
    // Collection view layout 
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init]; 
    layout.itemSize = CGSizeMake(100, 100); 
    layout.headerReferenceSize = CGSizeMake(320, 50); // Left for the switch 
    layout.minimumInteritemSpacing = 5; 
    layout.minimumLineSpacing = 5; 
    layout.scrollDirection = UICollectionViewScrollDirectionVertical; 
    layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5); 

    if (self = [super initWithCollectionViewLayout:layout]) { 
    // Collection view setup 
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"ID"]; 
    self.collectionView.frame = CGRectMake(0, -20, 320, 480-20-44-49); 
    self.collectionView.backgroundView = nil; 
    self.collectionView.backgroundColor = [UIColor clearColor]; 
    ... 
    } 
    return self; 
} 

然后,我实现了两个委托方法:

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { 
    return [blogs count]; 
} 

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionViewArg cellForItemAtIndexPath:(NSIndexPath *)indexPath { 
    UICollectionViewCell *cell = [collectionViewArg dequeueReusableCellWithReuseIdentifier:@"ID" forIndexPath:indexPath]; 
    /* Some code to get blogView */ 
    [cell.contentView addSubview:blogView]; 
    return cell; 
} 

回答

8

问题是有没有日志说,头不能是零因此,在那里给一些有效的输入,你可以避免崩溃。

一样,如果标题部分不需要输入给它clearclolor

的视图对于implementhing您必须实现以下数据源方法

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

编码愉快:)

+0

这代表标题节我应该用这个方法吗?你能给我一些示例代码吗?谢谢! – zhengwx 2013-02-20 05:48:46

+0

请放在你的代码...可能是我可以指出什么是丢失 – 2013-02-20 05:49:56

+0

我把代码放在另一个答案。谢谢! – zhengwx 2013-02-20 05:57:34