Search code examples
iosswiftuitextviewsegueuistoryboardsegue

Pass text to TextView via Segue


I'm trying to pass text to TextView from other ViewController:

    if (segue.identifier == "HomeToDetails") {
        let nav = segue.destination as! UINavigationController
        let nextVC = nav.topViewController as! DetailsViewController
        nextVC.infoTextView.text = "TESTING"
    }

But it crashes:

fatal error: unexpectedly found nil while unwrapping an Optional value


Solution

  • setting text on UITextField of DestinationViewController is not possible in the prepareForSegue:sender, because all view components of the recently allocated controller are not initialized before the view is loaded (at this time, they are all nil), they only will be when the DestinationViewController view is loaded.

    You need to use optional variable infoString in DetailsViewController which you can set in prepareForSegue method

    if (segue.identifier == "HomeToDetails") {
            let nav = segue.destination as! UINavigationController
            let nextVC = nav.topViewController as! DetailsViewController
            nextVC.infoString = "TESTING"
    }
    

    in DetailsViewController.swift

    class DetailViewController: UIViewController {
    
      var infoString: String?
    
      override func viewDidLoad() {
         super.viewDidLoad()
    
         if let info = infoString {
             self.infoTextView.text = info
         }
       }
    
    }