Yevgeni
Yevgeni

Reputation: 1533

Reusable items in collection view wont show the custom cell view properly

I have a collection view with costumed cells that contains an image view and a label, the label is a value i set in a "detail" control view, if i don't set it it shouldn't appear (as you can see in the picture). (btw Im using core data) .

The problem is with the labels(the smaller circles) , as soon as i remove a cell or add another one, some of the labels will appear and some not. Only when i'm restarting the app it all shows up again.

the relevant code from collectionview class:

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString* identifier =@"cell";
    THCollectionEnrtyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

    THDiaryEntry *entry = [self.fetchedResultsController objectAtIndexPath:indexPath];
    [cell configureCellForEntry:entry];
    return cell;
}

the relevant code from cell class:

- (void)configureCellForEntry:(THDiaryEntry *)entry {


    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"EEEE, MMMM d yyyy"];
   // NSDate *date = [NSDate dateWithTimeIntervalSince1970:entry.date];

   // self.dateLabel.text = [dateFormatter stringFromDate:date];

    self.mainImageView.frame = self.contentView.bounds; //fill it even tho we dont realy need

    if (entry.imageData) {
        self.mainImageView.image = [UIImage imageWithData:entry.imageData];
    } else {
         self.mainImageView.image = [UIImage imageNamed:@"icn_noimage"];
    }



    self.mainImageView.layer.cornerRadius = CGRectGetWidth(self.mainImageView.frame) / 2.0f;
    self.weightLabel.layer.cornerRadius = CGRectGetWidth(self.weightLabel.frame)/ 2.0f;
    self.weightLabel.text = entry.weight;
    if ([self.weightLabel.text isEqualToString:@"n/a"] || [self.weightLabel.text isEqualToString:@""] ) {
        self.weightLabel.hidden = YES;
    }
}

enter image description here

I'm pretty sure it has to do with the reusability of cells (i notice it when i add a cell with no value and then some other cells who have values doesn't appear with my labels), Any ideas how to handle it ?

Upvotes: 0

Views: 617

Answers (1)

Alex
Alex

Reputation: 1625

It's hard to know exactly the behavior your are experiencing from the description. One thing I noticed is you are setting self.weightLabel.hidden = YES; under certain circumstances, but you never set this to NO otherwise. This could be the reason reused cells are not displaying your weightLabel sometimes.

Consider implementing - (void)prepareForReuse for you UICollectionViewCell subclass. This will allow you to return a cell to a known, default state before reuse and you will be able to keep the logic of - (void)configureCellForEntry:(THDiaryEntry *)entry a bit simpler.

Upvotes: 1

Related Questions