简体   繁体   中英

Change UICollectionViewCell content and nib layout based on data

I have a UICollectionView that is displaying many UICollectionViewCells that I have subclassed as CardCell. I pass the variable "type" to the CardCell in - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath I want the CardCell class to be able to load a different Nib file depending on what type is passed in. The different types need to have different layouts.

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

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

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

Then, in itemForRowAtIndexPath, test for type and return the correct type of cell:

 - (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;
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM