There are several ways to do this, I believe the easiest way is to pass the value via attribute.
Declare in Viewcontroller1 as attribute the value you want to pass.
var numeroAleatorio = 4
In Viewcontroller 2, create an attribute that receives the value of Viewcontroller1.
var viewController1: ViewController!
As in this case you will NOT initialize the variable, you NEED to use the ! operator which means that the variable is optional. If you don’t use, Swift will ask you to initialize the variable which is not your intention, since it has already been started in Viewcontroller1.
The type of this variable has to be the class of its Viewcontroller1.
Now, let’s show on your screen your Viewcontroller 2 from Viewcontroller1.
let v2 = ViewController2()
v2.viewController1 = self
self.presentViewController(v2, animated: true, completion: nil)
Note that in
v2.viewController1 = self
you are pointing out the value of the viewController1 attribute you created in your Viewcontroller2 for your first view.
With the pointer to your first variable, it is extremely easy to access ANY attribute of the first view variable.
NSLog("%d", viewController1.numeroAleatorio)
If you start having two more views, it might be interesting to research Singleton.
I recommend you also study ways to persist your information like Coredata and Nsuserdefaults.
Thanks, Carl, I’ll test it here. for Coredata I chose not to save the value because it is temporary, what will be saved is the result of the function that is in View2
– Fábio Reibnitz
gave error v2.viewController1 = self that v2 cannot receive uncle v1
– Fábio Reibnitz
you set v1 as Uiviewcontroller or as Viewcontroller? The type of v2.viewController has to be the type of your first view.
– Carl Brusell
Sorry Carl, as I’m starting at IOS I ended up getting confused, the classes are Uiviewcontroller type.. I’ll rephrase the question
– Fábio Reibnitz
What is the name of your first view? Pass me the line you declared the attribute viewController1
– Carl Brusell
edited the question again
– Fábio Reibnitz
Fabio, look for prepare, bemmmmmmmmmmm is easier.
– JdsMedeirosBR
@Jadsonmedeiros Thank you very much, at first it was a bit confusing the materials I found, but this link gives to understand very well http://jamesleist.com/ios-swift-passing-data-between-viewcontrollers/
– Fábio Reibnitz