1

I have a ViewController called VCA in which will add a subview VCB. This VCB is a xib generated file that asks for more specific user input by allowing the user to tap a few buttons. What i am having trouble with is determining how i am to pass the values that the user has selected back to VCA. Any help would be great

Alan
  • 87
  • 1
  • 9

2 Answers2

4

The most flexible approach is to create a @protocol that viewControllerA will adopt, add a delegate to viewControllerB, and when you initialize viewControllerB, do something in the form:

viewControllerB.delegate = viewControllerA

In viewControllerB, invoke that protocol:

self.delegate.doSomething()

By using a protocol, you can pass data without tying the two classes together ; there are a few good locations to set the delegate after creating viewControllerB, such as after its creation or prior a segue.

SwiftArchitect
  • 47,376
  • 28
  • 140
  • 179
  • Thanks For Your Help @SwiftArchitect! – Alan Aug 10 '15 at 16:04
  • One More Thing, attributes in viewControllerA become nil after i go about this process. Do you have any thought as to why? Is it my viewDidLoad()? – Alan Aug 10 '15 at 16:40
  • This is a different question which I would gladly answer. Please open a different question, put a link to it in a comment, and make sure you post some code! – SwiftArchitect Aug 10 '15 at 21:18
0

You could easily create a singleton to share data between your View Controllers. Luckily, it's very simple in Swift.

Like so:

class MySingleton() {
     static let sharedData = MySingleton()
     var aVariable: Int = 4         

     init() {}
}

You can then invoke the singleton anywhere with:

let ms = MySingleton.sharedData

and call properties with:

var newVar = ms.aVariable

Cole
  • 2,641
  • 1
  • 16
  • 34