问题
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