简体   繁体   中英

Swift 2, UiCollectionview after scrolling - changed cells data

For cells I just put info from array:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

            let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! ImagesCollectionViewCell

            if cell.dateLabel.text == "" {
                cell.dateLabel.text = imagesDatas[indexPath.row].datesStr
                cell.image.image = imagesDatas[indexPath.row].images
            }
            return cell
        }

To array, I generate data in DidAppear. Only one time. But When I scrolling collectionView - cells change data, for example:

1 cell - PictureA

2 cell - PictureB

then scrolling, and in collectionview will see:

1 cell - PictureB

2 cell - PictureA

then scrolling, and in collectionview will see again:

1 cell - PictureA

2 cell - PictureB

Can't understand what happen here...

the reason is table view dequeue your cell for optimization so you last cell dequeue. you should complete your code like this :

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! ImagesCollectionViewCell

        if cell.dateLabel.text == "" {
            cell.dateLabel.text = imagesDatas[indexPath.row].datesStr
            cell.image.image = imagesDatas[indexPath.row].images
        }
          else { 
                cell.dateLabel.text = "" ( (or another string)
                cell.image.image = nil(or another image)

            }

        return cell
    }

Remove your check. Since cells are reused. You need to set the data every time

 let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! ImagesCollectionViewCell


 cell.dateLabel.text = imagesDatas[indexPath.row].datesStr
 cell.image.image = imagesDatas[indexPath.row].images

 return cell
override func prepareForReuse() {
    super.prepareForReuse()

      cell.dateLabel.text = nil
        cell.image.image = nil

}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM