0

Two view controllers:

Two view controllers

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (sender as! cell1).name.text == "ww"{
            let s = segue.destination as! DetailViewController
            s.detail?.text = "wwwwwwwwwww"
        }
    }

I am new to coding. What I am trying here is to communicate between view controllers. For some reason, I am not able to show the wwwwwwwwwww in the label of the second view controller

boop_the_snoot
  • 3,209
  • 4
  • 33
  • 44
jsr
  • 3
  • 2

1 Answers1

0

At the prepare function the view hasn't been loaded yet from storyboard, so the outlets of the DetailViewController are still nil. Create a public variable in the DetailViewController which will be available at prepare, then in the viewDidLoad method of DetailViewController you can set the label's text to be the content of that variable.

class DetailViewController: UIViewController {

   var text: String?

   override function viewDidLoad() {
       super.viewDidLoad()
       label.text = text
   }
}

Then in your list viewcontroller set the text property of detail vc:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    guard (sender as! cell1).name.text == "ww",
        let detailVc = segue.destination as? DetailViewController
        else { return }

    detailVc.text = "wwwwwwwwwww"
}
danieltmbr
  • 1,022
  • 12
  • 20
  • Thanks. But isn't 'detail' also a property of DetailViewController. Being an outlet is just one more way if updating it – jsr Oct 05 '17 at 00:50
  • Yes, but 'detail' property is an Interface Builder Outlet which will be nil until the viewDidLoad methods (since that time the view hasn't been loaded yet, so none of its outlets are binded to the code yet), after viewDidLoad you can access the detail property which represents a UILabel in your case, but not before that. And since performSegue is happening before the DetailsVc viewDidLoad you can't access the 'detail' label from code at that time. – danieltmbr Oct 05 '17 at 06:37
  • Life cycle o a UIViewController: https://stackoverflow.com/questions/5562938/looking-to-understand-the-ios-uiviewcontroller-lifecycle – danieltmbr Oct 05 '17 at 06:38