Change UICollectionViewCell content and nib layout based on data

混江龙づ霸主 提交于 2020-01-03 05:54:06

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/17711452/change-uicollectionviewcell-content-and-nib-layout-based-on-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!