Scroll through collectionView to move cell's subview to another cell

Asked 1 years ago, Updated 1 years ago, 107 views

When I scroll through the collectionView, the cell's subview moves to a different cell.

Obtain photos of the camera roll and place them in order in the collectionview.
I am writing about tapping the placed cell to add the subview to the cell like twitter.

#pragma mark-UICollectionViewDataSource

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

    PHAsset*asset=self.assets [indexPath.item];

    CameraRollCell*cell=(CameraRollCell*) [collectionView requestReusableCellWithReuseIdentifier:cameraRollCellID forIndexPath:indexPath];

    [self.imageManager requestImageForAsset:asset]
                                 targetSize —self.cellSize
                                contentMode—PHImageContentModeDefault
                                    options:nil
                              resultHandler:^(UIImage* result, NSDictionary* info) {
                                  if(result){
                                      cell.backgroundView=[[UIImageView alloc] initWithImage:result];
                                  }
                              }];

    return cell;
}

- (void) collectionView: (UICollectionView*) collectionView didSelectItemAtIndexPath: (NSIndexPath*)indexPath{
    PHAsset*asset=self.assets [indexPath.item];

    CameraRollCell*cell= (CameraRollCell*) [collectionView cellForItemAtIndexPath:indexPath];
    cell selectPhoto;
}

That's why I wrote this action. Calling selectPhoto runs the process of adding a subview to yourself in a custom cell.

This is what happens when you add it.
Normal

It will be successfully completed until the addition, but if you scroll through the collectionview, the imageView will remain the same and the added subView will be moved to a different cell.
Abnormal

How can I prevent this problem from occurring?
I look forward to hearing from you.

ios objective-c uicollectionview uicollectionviewcell

2022-09-30 19:33

1 Answers

When the image is retrieved, the cell may become a different cell, or the previous UIImageView may remain on the reused cell.

Wouldn't it be better to put the UIImageView on the cell from the beginning, get the cell from the table with indexPath, and set the image in the cell of the specified line?The link below is an example of UITableView, but I think it will be helpful.
ios-Async image loading from url inside a UITableView cell-image changes to wrong image while scrolling-Stack Overflow


2022-09-30 19:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.