Passing variable back to parent in Swift

前端 未结 2 428
礼貌的吻别
礼貌的吻别 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
        }
    }
    
    0 讨论(0)
  • 2021-02-08 15:21

    It's possible that the view controller returned by ViewController() has not yet loaded its views. You could try checking this in a setter function and storing it for later use once the views have been loaded.

    class VC : UIViewController {
        @IBOutlet weak var colourLabel: UILabel!
        var savedLabelText: String?
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            self.colourLabel.text = self.savedLabelText
        }
    
        func setColorLabelText(label: String) {
            if self.isViewLoaded() {
                self.colourLabel.text = label
            }
            else {
                self.savedLabelText = label
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题