2013-03-08 30 views
1

我有一個數組有10個條目。我想在UICollectionView顯示它們在每行3所以他們會像使用UICollectionView在iphone

A B C 
D E F 
G H I 
J 

現在,我使用下面的代碼

#pragma mark - UICollectionView Datasource 

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath 
{ 

} 

- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section 
{ 
    return 3; 
} 

- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView 
{ 
    return [self.btnArray count]; 
} 

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UICollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath]; 

    Buttons *btn = [self.btnArray objectAtIndex:(indexPath.section * indexPath.row)]; 
    NSURL* aURL = [NSURL URLWithString:btn.imagePath]; 
    NSData* data = [[NSData alloc] initWithContentsOfURL:aURL]; 

    cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithData:data]]; 
    return cell; 
} 

#pragma mark – UICollectionViewDelegateFlowLayout 

// 1 
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    CGSize retval = CGSizeMake(75, 75); 
    return retval; 
} 

// 3 
- (UIEdgeInsets)collectionView: 
(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section 
{ 
    return UIEdgeInsetsMake(50, 20, 50, 20); 
} 

但是當我打

UICollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath]; 

它給me error

NSInternalInconsistencyException', reason: 'could not dequeue a view of kind: UICollectionElementKindCell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard' 

有什麼不對?

+0

聽起來好像它告訴你如何解決它。你做過這些嗎? – 2013-03-08 15:39:56

+0

@CarlNorum http://www.raywenderlich.com/22324/beginning-uicollectionview-in-ios-6-part-12我正在使用預製佈局? – 2013-03-08 15:44:52

回答

3

如錯誤所述,您需要爲具有該標識符的單元格註冊一個筆尖或類。您在設置視圖時只需執行一次。

見這兩種方法的UICollectionView文檔:

– registerClass:forCellWithReuseIdentifier: 
– registerNib:forCellWithReuseIdentifier: 
+0

你可以進一步解釋我的代碼中要編輯什麼嗎? – 2013-03-08 16:07:46

+0

你會在你的viewDidLoad方法中調用這些方法之一。如果您的單元格使用.xib文件,則使用registerNib方法。如果不是,則使用registerClass方法。閱讀文檔,它會解釋更多。無論何時出現這樣的問題,文檔都非常有用。 – Dancreek 2013-03-08 16:16:28

相關問題