Access the instance of a Viewcontroller from another in swift

前端 未结 3 1992
刺人心
刺人心 2020-12-04 18:21

I am trying to transfer data from the textfield of one View Controller to the label from another.

How can I call the View Controller instance from the code of the o

3条回答
  •  悲&欢浪女
    2020-12-04 18:49

    You need to create a Segue between View Controllers:

    1. On your Storyboard, select ViewController A.
    2. While holding the Control, click ViewController A, drag and drop the blue line to ViewController B. If ViewController A is embedded in a NavigationController, select "show" from the menu that appears when you let go. Otherwise, select "present modally."
    3. Select the Segue on your Storyboard, and on the Utilities Panel, go to the Attributes Inspector and assign an Identifier for your segue (e.g.: "DetailSegue").

    Now, when you want to trigger the segue on ViewController A, you just need to call (maybe on the tap of a button):

    @IBAction func buttonTapped() {
        self.performSegueWithIdentifier("DetailSegue", sender: self)
    }
    

    To pass a value to ViewController B, override the prepareForSegue:sender method on ViewController A:

    override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
        if segue.identifier == "DetailSegue" {
            var viewControllerB = segue.destinationViewController as ViewControllerB
            viewControllerB.text = self.textField.text
        }
    }
    

    Pretty straightforward.

    Note that for this to work, your ViewController B class should look something like this:

    class ViewControllerB: UIViewController {
        ver label = UILabel(...)
        var text: String? 
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            label.text = text!
        }
    }
    

    Hope this helps.

提交回复
热议问题