First, note:. Your names for view controllers should include a "ViewController". There is a completely different collection of classes inheriting from UIView . Naming the view controller simply ViewA makes it look like your class is just a view instead of a view controller. Views are in a completely different layer of your application.
Now, to transfer data to another object , your first requirement is to have a link between them. This link can be configured in any direction.
One possibility is for ViewControllerA to maintain a link to ViewControllerB. Using this link, ViewControllerA can invoke a method on ViewControllerB when a button is pressed that accepts the data you want to pass as an argument.
class ViewControllerA: UIViewController { @IBOutlet weak var viewControllerB: ViewControllerB! @IBAction func addButton(sender: AnyObject) { self.viewControllerB.showNameLabel(textField.text) } }
Another possibility is to use a delegate template, as your header suggests. This will include ViewControllerB with reference to ViewControllerA. Preferably, this is not due to direct knowledge of the ViewControllerA class, but instead through the protocol. The protocol will define a method that returns the data you want to pass to ViewControllerB. Thus, ViewContollerB can call the protocol method in its "delete" (which is likely to be ViewControllerA) to get the data it needs.
protocol ViewControllerBDelegate { func requiredText() -> String } class ViewControllerB: UIViewController { @IBOutlet weak var delegate: ViewControllerBDelegate? override func viewDidLoad() { if let actualDelegate = self.delegate { self.theLabel.text = actualDelegate.requiredText() } } }
Which method you choose really depends on what you need in this case. In a delegate template, it's best to keep your objects less connected to each other, but if you already need to “run” something that needs to happen on ViewControllerB from ViewControllerA, you may need a more direct method.
drewag
source share