I made a gallery for training:

alt text

I want to organize the opening of the image in full screen when clicked. I have already done the discovery myself, but I had a problem: for the first time, the image under the index 0 always opens, and the next time, the image that I clicked on before. The code looks like this:

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { [collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionCenteredHorizontally]; selectedPhotoIndex = indexPath.row; NSLog(@"%li", selectedPhotoIndex); } - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if([segue.identifier isEqualToString:@"fullAttachShow"]){ DetailShowViewController *detailViewController = segue.destinationViewController; detailViewController.fullImage = selectedPhotoIndex; NSLog(@"%li", (long)detailViewController.fullImage); } } 

As I understand it, the following method is called when I click: - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
and only then: -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

And it turns out that the next time I see the picture that was supposed to open before that.

How do I get the first to work when the user clicks -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath and then - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender ?

    1 answer 1

    Perhaps you have a separate segue on each cell, in this case it’s worth removing all the segways and adding a new one between the gallery controller and the controller in which the picture opens. And change the methods:

     - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { [collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionCenteredHorizontally]; selectedPhotoIndex = indexPath.row; UIImage *image = self.images[indexPath.row]; [self performSegueWithIdentifier:@"DrawToDetail" sender:image]; NSLog(@"%li", selectedPhotoIndex); } - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if([segue.identifier isEqualToString:@"fullAttachShow"]){ DetailShowViewController *detailViewController = segue.destinationViewController; detailViewController.fullImage = (UIImage*)sender; } } 
    • Unfortunately, CollectionView does not have information about which image was poked. He knows only id. So I need to pass an id. I pass the id here: detailViewController.fullImage = selectedPhotoIndex; - Gool
    • Then you need to replace detailViewController.fullImage = (UIImage *) sender; on detailViewController.imageIndex = selectedPhotoIndex; - Koby
    • Everything worked out! Thank you! - Gool