vampyfreak vampyfreak - 11 days ago 6
Swift Question

How to pass Image from from TableViewCell to UIImage

My seguesI am trying to figure out if there is a way for me to pass image in the cell that I select to a new

UIImageView
in a completely different view controller. I dont fully understand how the segue works and after hours of deliberation I have not yet fully found a solution. I have been able to display my images in the
tableview
, but I want to send the selected image to the
UIImageView
for a bigger view of the picture. I currently have 2 VCs for this. The first of them is called TableView

import UIKit

class TableView: UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {


@IBAction func toImage(_ sender: Any) {
performSegue(withIdentifier: "ImageView", sender: self)
}

// Properties
var imagesDirectoryPath:String!
var images:[UIImage]!
var titles:[String]!

@IBAction func choosePhoto(_ sender: AnyObject) {
let imagePicker = UIImagePickerController()
if UIImagePickerController.isSourceTypeAvailable(.camera){
imagePicker.sourceType = .photoLibrary
print("Library selected")
}else{
print("No cam here!")
}

present(imagePicker, animated: true, completion: nil)
imagePicker.delegate = self

}

override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self

self.tableView!.register(UITableViewCell.self, forCellReuseIdentifier:"CellID")

images = []

let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
// Get the Document directory path
let documentDirectorPath:String = paths[0]
// Create a new path for the new images folder
imagesDirectoryPath = documentDirectorPath + "/ImagePicker"
var objcBool:ObjCBool = true
let isExist = FileManager.default.fileExists(atPath: imagesDirectoryPath, isDirectory: &objcBool)
// If the folder with the given path doesn't exist already, create it
if isExist == false{
do{
try FileManager.default.createDirectory(atPath: imagesDirectoryPath, withIntermediateDirectories: true, attributes: nil)
}catch{
print("Something went wrong while creating a new folder")
}
}
}


override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

func refreshTable(){
do{
images.removeAll()
titles = try FileManager.default.contentsOfDirectory(atPath: imagesDirectoryPath)
for image in titles{
let data = FileManager.default.contents(atPath: imagesDirectoryPath + "/\(image)")
let image = UIImage(data: data!)
images.append(image!)
}
self.tableView.reloadData()
}catch{
print("Error")
}
}


//MARK: UIImagePickerControllerDelegate Protocol
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {

// Save image to Document directory
var imagePath = Date().description
imagePath = imagePath.replacingOccurrences(of: " ", with: "")
imagePath = imagesDirectoryPath + "/\(imagePath).png" //this would change depending on the name of the image
let data = UIImagePNGRepresentation(image)
_ = FileManager.default.createFile(atPath: imagePath, contents: data, attributes: nil)
dismiss(animated: true) { () -> Void in
self.refreshTable()
}
}

//MARK: UITableView DataSource
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: "CellID")

cell?.imageView?.image = images[indexPath.row]
cell.textLabel?.text = titles[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return images.count
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "ImageView", sender: images[indexPath.row])
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
var secondVC : ImageView = segue.destination as! ImageView

//secondVC.fullView = imagesDirectoryPath[IndexPath.row]
}



}


This is my
ImageView
, where I want my image from the cell to appear.

import UIKit

class ImageView:ViewController{

@IBOutlet var fullView: UIImageView!
var selectedImage = UIImage()
override func viewDidLoad() {
super.viewDidLoad()
self.fullView.image = self.selectedImage //Assign selected Image here




}
//segue via a button
@IBAction func toTable(_ sender: Any) {
performSegue(withIdentifier: "TableView", sender: self)

}


}


So is there any way that I could pass the existing image to an
UIImageView
in an another VC. I combed through all over Google, but I cant seem to get figure it out.

Thanks!

Answer

In your storyboard file make sure the custom class is set to SecondViewController on the segue destination's nib:

enter image description here