简体   繁体   中英

Passing data between tabbed views in swift

I have a project that has a tabbed bar controller that is linked to a FirstViewController.swfit and a SecondViewController.swift.

I have a textbox in the first view, and in the second view I have a label and a button. I want the user to be able to type something in the textbox in the first view, then switch over to the second tab, and press the button and have whatever they typed in the textbox appear in the label.

I have tried researching all over the place and I came across segues and singletons, but I am not sure how to exactly apply those or if they are even necessary for what I'm trying to achieve.

Thank you!

EDIT

My SecondViewController.swift code based on razor's reply:

import UIKit

class SecondViewController: UIViewController {

var firstViewController: FirstViewController?

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBOutlet weak var label: UILabel!

@IBAction func button(sender: AnyObject) {

    if let fvc = firstViewController {
        self.label.text = fvc.textbox.text
    }

}
}

A common practice is for SecondViewController to have a reference to FirstViewcontroller. So within the ViewController class, you'd have eg an optional variable like:

var firstViewController: FirstViewController?

Then, when you handle the button press, you can do something like

if let fvc = firstViewController {
  self.label.text = fvc.textbox.text
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM