Passing variable back to parent in Swift

前端 未结 2 427
礼貌的吻别
礼貌的吻别 2021-02-08 14:28

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

2条回答
  •  被撕碎了的回忆
    2021-02-08 15:12

    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
        }
    }
    

提交回复
热议问题