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
Problem is in this line
detailCrystalPhotoImageView.image = UIImage(named: img)
. Here argumentnamed
is string type. Here you are passingimg
whichUIImage
type. So you can fix this byYour
img
variable declared in theDetailViewController
is of typeUIImage
. TheUIImage(named: img)
method expects a string name of the image, not an image object itself.You have to directly set the image like so,