Haris Haris - 4 months ago 26
iOS Question

IOS Collection View load Image from custom cell class

I am trying to implement custom collection view with custom class for each cell. Below code works fine, where the image is loading from Collection view class itself.

customCollectionView.m

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = @"Cell";


MyCell *cell = (MyCell *)[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];


UIImage *Img = [UIImage imageNamed:[Images objectAtIndex:indexPath.row]];
cell.myImageView.image = Img;
cell.layer.borderWidth=2.0f;
cell.layer.borderColor=[UIColor lightGrayColor].CGColor;
return cell;
}


MyCell.m

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}


Whereas when I moved the image loading part to custom
CollectionViewCell
class
MyCell
the image is not displaying.

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
UIImage *Img = [UIImage imageNamed:@"AppIcon.png"];
_myImageView.image = Img;

}
return self;
}


My final purpose is loading different image from MyCell class in specific time interval and display on each cell.

Answer

Try to implement prepareForReuse method of UICollectionViewCell inside your customCell MyCell

-(void)prepareForReuse {

    _myImageView.image = [UIImage imageNamed:@"AppIcon.png"];
}

Try awakeFromNib and remove prepareForReuse

- (void)awakeFromNib {
    _myImageView.image = [UIImage imageNamed:@"AppIcon.png"];
}