swiftuitableviewdelegatesdidselectrowatindexpath

Delegate is Nil with UITableView


I'm new to Swift and am trying to learn delegates in combination with UITableViews. I have 2 scenes: A Home Scene (UIViewController) that has an image and a button. The button advances to the second scene: Selection Scene (UITableViewController). In each of the TableviewCells I have an image where the user will select and I then want to segue back to the Home screen where that image will be loaded into the image location. I have everything embedded into a Navigation Controller. The delegate keeps coming up nil and I can't figure out why...Thank you

"Selection Scene - Sender"

 protocol TableViewControllerDelegate : class {

func passBackInformation (image: UIImage, name: String)

}

class TableViewController: UITableViewController {


weak var tableViewControllerDelegate : TableViewControllerDelegate?

...

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
    let image = UIImage(named: productArray[indexPath.row].imageName)!
    let name = productArray[indexPath.row].productName
    
    if self.tableViewControllerDelegate != nil {
        self.tableViewControllerDelegate?.passBackInformation(image: image, name: name)
    }else{
        print("Still no delegate")
    }

Here is the code in my delegate (UIViewController) - Receiver

class ViewController: UIViewController, TableViewControllerDelegate {

func passBackInformation(image: UIImage, name: String) {
        frontProductImage.image = image
        frontLabel.text = name
        
    }

@IBAction func frontBUtton(_ sender: Any) {
        
        let selectionVC = storyboard?.instantiateViewController(withIdentifier: "SelectProduct") as! TableViewController
        
        selectionVC.tableViewControllerDelegate = self
        dismiss(animated: true, completion: nil)
       }

Solution

  • In the IBAction called frontBUtton(), the view controller is being instantiated and the delegate is set. But then the new view controller is immediately dismissed.

    Rather than dismissing the view controller, present it:

    present(selectionVC, animated: true, completion: nil)
    

    After passing the data back in the tableview controller, then, dismiss the view controller here like this:

        if self.tableViewControllerDelegate != nil {
                self.tableViewControllerDelegate?.passBackInformation(image: image, name: name)
                dismiss(animated: true, completion: nil)
            }else{
                print("Still no delegate")
            }