I have a UIViewController
in which I have a UICollectionView
.The cells of the UICollectionView
need to be images so I understand that I need to subclass the UICollectionViewCell
class. So basically, I need a UIViewController which has a UICollectionView that has a custom UICollectionViewCell. I am using a storyboard and when I need to create a custom UITableVieCell
, I do the following:
UITableViewCell
UITableViewCell
in the storyboard But when I follow the same for a UICollectionViewCell
, for eg. I create a subclass called CustomCollectionViewCell
, and declare it in the cellForItemAtIndexPath
like
CustomCollectionViewCell *cell = (CustomCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
NSLog(@"%@",cell);
This logs <UICollectionViewCell: 0x137529010; frame = (10 10; 300 164); layer = <CALayer: 0x170220880>>
<UICollectionViewCell: 0x137529010; frame = (10 10; 300 164); layer = <CALayer: 0x170220880>>
<UICollectionViewCell: 0x137529010; frame = (10 10; 300 164); layer = <CALayer: 0x170220880>>
no matter what I do. I can just not initialize my custom UICollectionViewCell
class and hence cannot add the images.
I looked at other StackOverflow answers and read answers saying not to do this:
[self.collectionView registerClass:[CustomCollectionViewCell class] forCellWithReuseIdentifier:@"Cell"];
if I'm using storyboard, so I commented it out.
All the reuse identifiers, outlets etc have been set. I can't seem to find where the error is.
Any help is appreciated.
Try this,
set your custom collectionview cell class in Identity Inspector
like
and in cellForItemAtIndexPath
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
CollectionViewCell *cell = (CollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
NSLog(@"%@", cell);
return cell;
}
and got log as
<CollectionViewCell: 0x7af70000; baseClass = UICollectionViewCell; frame = (0 0; 70 69); clipsToBounds = YES; opaque = NO; layer = <CALayer: 0x7af70210>>
I figured it out.
It was a stupid mistake. The reuse identifier that I was using was already being used by a different cell someplace else. Changed it and it works perfectly now.
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.