Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variable back to parent in Swift

Tags:

xcode

ios

swift

I am re-writing a tutorial converting the code from Objective-C to swift. The app moves from VC one where there is 3 sliders (Red, Green and Blue) that set the background colour, a label of the colour name and a button that links to the second VC. In the second VC the colour from the first VC is used as the background and the user has a chance to name the colour.

When the user enters the colour name it should return the new colour name to the orginal VC and the label that shows the colour name should show the text entered.

The following is the code that is causing issue:

func textFieldShouldReturn(nameEntry: UITextField) -> Bool
{
    ViewController().colourLabel.text = nameEntry.text
    nameEntry.resignFirstResponder()
    dismissViewControllerAnimated(true, completion: nil)
    return true
}

The error "fatal error: unexpectedly found nil while unwrapping an Optional value" is generated. However debugging nameEntry.text has a string in it.

I'm a little stumped. I could try and do a prepare for unwind segue but it is meant to be a tutorial app.

Cheers

like image 946
LittleJohnD Avatar asked Feb 12 '15 11:02

LittleJohnD


1 Answers

ViewController() actually creates a new instance of your ViewController. This is not a reference to the already existing ViewController. What you can do is create a weak variable pointing to first ViewController inside the second ViewController and set it at prepareForSegue or when the second View controller is shown.

class SecondViewController : UIViewController {
    weak var firstViewController : ViewController?

    // Other code

    func textFieldShouldReturn(nameEntry: UITextField) -> Bool
    {
        firstViewController?.colourLabel.text = nameEntry.text
        nameEntry.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
        return true
    }
}

Inside First View Controller prepareForSegue

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "SecondViewController" {

        let secondViewController = segue.destinationViewController as SecondViewController
        secondViewController.firstViewController = self
    }
}
like image 128
rakeshbs Avatar answered Oct 05 '22 13:10

rakeshbs