tranvutuan
tranvutuan

Reputation: 6109

can not set title for cell at specific indexPath.row of uicollectionview, UICollectionView

When working on UICollectionView, I am loading a cell from nib like below

- (void)viewDidLoad
{
    [super viewDidLoad];
    /* Uncomment this block to use nib-based cells */
    UINib *cellNib = [UINib nibWithNibName:@"NibCell" bundle:nil];
    [self.collectionView registerNib:cellNib forCellWithReuseIdentifier:@"cvCell"];


    // Configure layout
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.collectionView.contentInset    =   UIEdgeInsetsMake(10.0f, 0.0f, 10.0f, 0.0f);

    [flowLayout setItemSize:CGSizeMake(300, 200)];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    [self.collectionView setCollectionViewLayout:flowLayout];
}

And my nib file looks like below

enter image description here

The top label is used to displayed the number of cell and the middle label is used to display a certain text

in method cellForItemAtIndexPath, I just want to set the text to the cell of certain row ( in this example, I am doing it at row of 1 ) :

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

     // Setup cell identifier
     static NSString *cellIdentifier = @"cvCell";

     UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
     UILabel *titleLabel    = (UILabel *)[cell viewWithTag:100];
     UILabel *cellLablel    = (UILabel *)[cell viewWithTag:200];
     cellLablel.text         =   self.dataArray[0][indexPath.row];
     if ( indexPath.row == 1)
         [titleLabel setText:@"this is row 1"];

    return cell;

}

When running the app, there is a problem on it. Not only is titleLabel of cell at row1 set to This is row 1, but also the titleLabel of row5 and row9 and row10 is set as well: enter image description here

enter image description here

If anybody knows what I am doing wrong in the middle. please help.

My colleciton is containing 1 section and 15 row for this section.

Upvotes: 2

Views: 2148

Answers (1)

chris
chris

Reputation: 3563

Cells are reused. As soon as you scroll down and Cell 1 gets invisible, the collection view makes it available again. Just set the text for all cells, e.g.

titleLabel.text = [NSString stringWithFormat:@"this is row %d", indexPath.row];

Upvotes: 3

Related Questions