Jess
Jess

Reputation: 275

How to display image of selected UICollectioNViewCell in UIView? (Swift 3)

I am new to iOS development, so please bear with me if this is obvious.

I have a UICollectionView on the bottom half of a view controller; it currently displays all photos in my photo library. There is a UIView on the top half of the same view controller.

Q: When I select a UICollectionViewCell (i.e. a photo), how do I display that photo in the UIView on the same view controller?

I imagine I'll have to use didSelectItemAt somehow to save the index path of the selected image in order to display that image in the UIView. (I've included what I have thus far for didSelectItemAt.) How do I refresh the content of the UIView as different photos are selected?

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let selectedVideo = collectionView.cellForItem(at: indexPath)
    selectedVideo?.alpha = 0.5
}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    let deselectedVideo = collectionView.cellForItem(at: indexPath)
    deselectedVideo?.alpha = 1.0
}

Upvotes: 1

Views: 7471

Answers (3)

anshul king
anshul king

Reputation: 568

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let selectedVideo = collectionView.cellForItem(at: indexPath)
    view.imageView.image = selectedVideo
}

Upvotes: 0

Vinod Kumar
Vinod Kumar

Reputation: 3385

put ImageView into your view then make IBOutlet of imageview . you get cell of collectionview , set image of collectionviewcell of imageview image into top imageView

You can try this

 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
            let selectedCell = collectionView.cellForItem(at: indexPath) as! MyCollectionViewCell
           yourview.imageView.image = selectedCell.imageView.image
        }

Upvotes: 5

jo3birdtalk
jo3birdtalk

Reputation: 616

From my understanding on the comments you have described earlier, there are 2 ways you can implement.

  1. Using UIViewController, drop a UIView and a UICollectionView.
  2. Using UICollectionViewController, and create a UICollectionReusableView

I'm assuming that you are using the 1st method,

Drop an @IBOutlet for the above UIImageView and name it myImageView for example.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let selectedImage = collectionView.cellForItem(at: indexPath)
        myImageView.image = selectedImage.myImageView.image
}

Upvotes: 2

Related Questions