Can't get UICollectionView to display cells

前端 未结 2 981
日久生厌
日久生厌 2021-01-02 13:56

I\'m trying to get a UICollectionView to display inside a modally presented view controller. The app is for iPad iOS 7.

I\'ve created subclass of UIViewController (w

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-02 14:49

    If you link your collectionView and its own dataSource and delegate in your xib file, you don't need to set up this on your code.

    Next, you need to register your UICollectionViewCell :

    - (void)viewDidLoad 
    {
        [super viewDidLoad];
    
        // Register Nib
        [self.collectionView registerNib:[UINib nibWithNibName:CollectionViewCell_XIB bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:CollectionViewCell_ID];
    }
    

    CollectionViewCell_XIB is the name of your cell xib CollectionViewCell_ID is the ID of your cell

    And you need to implement cellForItemAtIndexPath like this :

    - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
    {
        CollectionViewCell *cell = (CollectionViewCell *)[self.collectionView dequeueReusableCellWithReuseIdentifier:CollectionViewCell_ID forIndexPath:indexPath];
    
        // Configure cell with data
         UIImageView *myImageView = (UIImageView *)[cell viewWithTag:100];
        myImageView.image = [UIImage imageNamed:[itemsArray objectAtIndex:indexPath.row]];
    
        // Return the cell
        return cell;
    }
    

提交回复
热议问题