Search code examples
iosswiftuicollectionviewuicollectionviewcellinstagram-api

Calling next image in collectionview from other class


I built an app that fetch all the photos from Instagram user via Instagram API and show them ordered in CollectionView.

Now, when the user tap on a photo the photo will open in a UIView to show that image - basically the user can pinch to zoom and other options that can't be in the Instagram app.

What I'm trying to do is - swipe the image to move to the next image. I thought about using ScrollView which is not a big deal.

THE PROBLEM IS that I don't know how to call the next photo in the collection view.


Solution

  • You can use delegation something like this, have your view displaying the image call nextPhoto() when need an the collection view will supply.

            struct Photo {
                var image:UIImage?
            }
    
            class CustomCollectionView: UICollectionViewController{
                var dataSource:[Photo]! = []
                var selectedIndex:NSIndexPath!
    
                override func viewDidLoad() {
                    super.viewDidLoad()
                }
            }
    
            extension CustomCollectionView: UpdatePhoto {
    
                func nextPhoto() -> Photo?{
                    let nextIndex = selectedIndex.row + 1
                     // update selected index
    
                    selectedIndex = NSIndexPath(forRow: nextIndex, inSection: 0)
                    return dataSource[selectedIndex.row];
                }
    
                func previousPhoto() -> Photo? {
                    let previousIndex = selectedIndex.row - 1
                    // update selected index
                    selectedIndex = NSIndexPath(forRow: previousIndex , inSection: 0)
                    return dataSource[selectedIndex.row];
                }
            }
    
            protocol UpdatePhoto {
                func nextPhoto() -> Photo?
                func previousPhoto() -> Photo?
            }
        class PhotoDisplayingView:UIView{
            var photo:Photo
            var delegate:UpdatePhoto?
    
            required init(photo:Photo){
                self.photo = photo
                super.init(frame: CGRect(origin: CGPointZero, size: photo.image!.size))
            }
    
            required init?(coder aDecoder: NSCoder) {
                    fatalError("init(coder:) has not been implemented")
                }
            }
         }
    

    You'll do something like this when handling the gesture var nextImage = delegate.nextPhoto()