skip to Main Content

I am trying to pass an image into a new view controller via a segue. I was able to transfer the title into the view controller, but I keep getting the error: "Cannot convert value of type ‘UIImage?.Type’ to expected argument type ‘String’". Here’s code:

import UIKit

class DetailViewController: UIViewController {

   var name = ""
    var img: UIImage?
    
    @IBOutlet weak var detailCrystalNameLabel: UILabel!
    @IBOutlet weak var detailCrystalPhotoImageView: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = name
        detailCrystalPhotoImageView.image = UIImage(named: img)

    }
}

This is the code from the view controller:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MainCollectionViewCell", for: indexPath) as! MainCollectionViewCell
        cell.crystalPhotoImageView.image = imageArray[indexPath.row]
        
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let vc = storyboard?.instantiateViewController(identifier: "DetailViewController") as? DetailViewController
        
        vc?.name = nameArray[indexPath.row]
        vc?.img = imageArray[indexPath.row]
        
        self.navigationController?.pushViewController(vc!, animated: true)
    }
}

2

Answers


  1. Problem is in this line detailCrystalPhotoImageView.image = UIImage(named: img). Here argument named is string type. Here you are passing img which UIImage type. So you can fix this by

    detailCrystalPhotoImageView.image = img
    
    Login or Signup to reply.
  2. Your img variable declared in the DetailViewController is of type UIImage. The UIImage(named: img) method expects a string name of the image, not an image object itself.

    You have to directly set the image like so,

    detailCrystalPhotoImageView.image = img
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search