Change content of UICollectionViewCell and nib layout based on data

I have a UICollectionView that displays a lot of UICollectionViewCells, which I have classified as CardCell. I pass the "type" variable to CardCell in - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath . I want the CardCell class to be able to load another Nib file depending on what type is being transferred. Different types must have different layouts.

The problem is that I cannot figure out where to change this in my CardCell.m. I tried using - (void)prepareForReuse , but that does not call if the user is not scrolling.

0
source share
1 answer

You should register each nib file you need with viewDidLoad, something like this (substituting the correct names for the nib file and identifier):

 [self.collectionView registerNib:[UINib nibWithNibName:@"RDCell" bundle:nil] forCellWithReuseIdentifier:@"FirstType"]; 

Then, in itemForRowAtIndexPath, check the type and return the correct cell type:

  - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { if (type = @"firstType") { FirstCell *cell = (FirstCell *) [collectionView dequeueReusableCellWithReuseIdentifier:@"FirstType" forIndexPath:indexPath]; return cell; }else{ SecondCell *cell = (SecondCell *) [collectionView dequeueReusableCellWithReuseIdentifier:@"SecondType" forIndexPath:indexPath]; cell.whatever ..... return cell; } } 
+1
source

Source: https://habr.com/ru/post/949695/


All Articles