Salah Salah - 25 days ago 9
Swift Question

Pass image from collectionview to VC

I've tried a lot of methods i couldn't get it to work

ViewController 1 have : Collectionview > Cell > image inside the cell

ViewController 2 want to display the image which in VC 1

When you click on cell it has segue to push you to VC 2

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

if segue.identifier == "popup" {

let viewController: friendpopup = segue.destination as! friendpopup
let indexPath = sender as! NSIndexPath
let nicknamex = self.nicknameArray[indexPath.row]
let usernamex = self.userArray[indexPath.row]
let photox = self.friendsphotos[indexPath.row] // the photos PFFiles i think


viewController.snick = nicknamex
viewController.suser = usernamex
viewController.sphoto = // ????
}


nickname and user works fine only the image i couldn't display it.

I tried when you click on cell it will send the image to var but isn't working

var photovar:UIImage!

didSelectItemAt( self.photovar = cell.profilepic.image)
then in prepareSegue( viewcontroller.sphoto = self.photovar)

isn't woking, Anyone could help me to fix that to display the image? Thanks

dfd dfd
Answer

Tightening up your code a bit....

First VC

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "popup" {
        if let vc = segue.destination as? friendpopup {
            let indexPath = sender as! NSIndexPath
            vc.snick = self.nicknameArray[indexPath.row]
            vc.suser = self.userArray[indexPath.row]
            vc.sphoto = self.friendsphotos[indexPath.row]
        }
    }
}

Second VC:

// making assumptions on variable types
var snick:String!
var suser:String!
var sphoto:UIImage!

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    // do work here
    if sphoto != nil {
        imageView.image = sPhoto
    } else {
        // set a default image here
    }
}

Most of this is similar to your code, but one last note - if the first 2 properties are coming across correctly, check in the first VC that you are pulling the image out properly.