0

I am trying to pass the data of which name was selected by the user in my ShipViewController to my ProfileViewController. I tried using closures to do so, but the title of the button in ProfileViewController (which presents the modal popover to ShipViewController) isn't changing to the name the user selects in ShipViewController.

Should it not be String --> () or is the way I instantiate my view controller incorrect?

(ShipViewController)

var completionHandler:((String) -> ())?

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "shipCell", for: indexPath) as! ShipViewCell

    if selectedIndex == indexPath.row {
        let result = completionHandler?(shipNames[selectedIndex!])
        self.dismiss(animated: true, completion: nil)
    }
}

(In viewDidLoad of ProfileViewController)
        let vc = storyboard?.instantiateViewController(withIdentifier: "ShipViewController") as! ShipViewController
    vc.completionHandler = { (text) -> ()in
        print(text)
        self.shipButton.setTitle(text, for: .normal)
    }
Kaushik Makwana
  • 1,329
  • 2
  • 14
  • 24
Aza
  • 63
  • 10

1 Answers1

1

Dismiss ShipViewController in didSelectItemAt

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let result = completionHandler?(shipNames[indexPath.item])
        self.dismiss(animated: true, completion: nil)
}

In ProfileViewController Don't assign to completionHandler in viewDidLoad

Assign to completion handler in prepare for segue

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showShip" {
        if let vc = segue.destination as? ShipViewController {
             vc.completionHandler = { (text) -> ()in
                  print(text)
                  self.shipButton.setTitle(text, for: .normal)
             }
        }
    }
}
RajeshKumar R
  • 15,445
  • 2
  • 38
  • 70