4

I am trying to familiarize with swift but I can't find how to pass data between views using Swift.

class ViewController: UIViewController {

@IBOutlet var field: UITextField
@IBOutlet var butt: UIButton

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    if let vc = segue.destinationViewController as? secondViewController {
        if(vc.lab != nil){
            vc.lab.text=self.field.text
            println(self.field.text)
    }
  }

and second view controller:

class secondViewController: UIViewController {

@IBOutlet var lab: UILabel

override func viewDidLoad() {
    super.viewDidLoad()

}

What I want to do is simply change the label in the second view with the text of the textfield of the first view. In this way does not give me any error but I do not change the label.

1 Answer 1

2

To me, this doesn't look like a Swift problem. It looks like a view lifecycle problem. At the time prepareForSegue: is called, the secondViewController has not loaded it's IBOutlets from the storyboard yet. A better solution would be to set some type of property on the file, like

vc.myLabelString = self.field.text

then in viewDidLoad of secondViewController assign the text to your label.

FYI: You can always check if a view controller has loaded it's view with vc.isViewLoaded()

Sign up to request clarification or add additional context in comments.

3 Comments

This is one of the reasons I don't like storyboard. It hides what actually is going on. Doing all in code it would be clear that the label isn't loaded at that time.
@dasdom I agree with you that it's a bit obfuscated, but in my opinion, it's not the responsibility of the presenting view controller to be dealing with the views of another VC in the first place. Ideally what would happen is VC 1 passes some model object to VC 2. Call it "StatePark." Upon load, VC 2 would then know to populate all its views with the various data contained within the StatePark model, like Name, Location, Image, Description, Indigenous animals, etc.
I totally agree. Still don't like storyboards. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.