I can’t figure out how to run code from different View Controller‘s .
I have created a new project, and would appreciate a quick response as its homework, and have to be done by tonight.
In my project I have two View Controller‘s named; viewcontroller1 and viewcontroller2, and have assigned them to two different custom classes.
Viewcontroller1 comes to screen it has two UIButtons, one for running the code, and the other one to push to viewcontroller2.
When user clicks the first UIButton I want that button to run the code below and display the results on a UILabel on my viewcontroller2.
The code creates random numbers using arc4random and then show’s random words in the UILabel. The code works for single page based apps, and is used under implementation.
So basically what i want is, when i click the first UIButton i want to display randomly created words on my UILabel in the viewcontroller2.
-(IBAction)button; {
int random_num;
random_num = (arc4random() % 5 - 1) + 1;
if (random_num == 1) {
label.text = @"hello1";
}
else if (random_num == 2) {
label.text = @"hello2";
}
else if (random_num == 3) {
label.text = @"hello3";
}
else if (random_num == 4) {
label.text = @"hello4";
}
}
The timelabel is the UILabel on my viewcontroller2.
Can you please be detailed in your answer. I am a beginner and might not grasp the concepts right away.
Example
User opens the app
Viewcontroller1 is shown
User press the button 1 which runs code for the label in the viewcontroller2
User press the button 2 to go to viewcontroller
Viewcontroller2 comes up and label on it has changed by the button
I know that it is not a hard thing to do but I can’t do it.
For those who answered me before and for those who will answer thank you soo much..
Thanks.
So, first of all I want to make it clear, it is not possible that viewcontroller1 comes to screen. Actually view of viewcontroller1 comes to screen. You see on the screen only the views and they belongs / controlled by viewcontrollers.
To answer you question correctly we need to know, what do you use to change the views? Do you use a navigation controller, tabbarcontroller or something else?
Commonly the labels, which is a UI element for presenting textes are initialized in viewDidLoad method of the viewcontroller. So setting text before that does nothing.
if you have reference to viewcontroller2 from viewcontroller1 you can create a property to hold the text and set it after pressing the button. And viewcontroller2 can present the text after loading the view on a label. So your code in viewcontroller1 looks like this
And your viewcontroller2 header file(ViewController2.h)
you viewController2 implementation file (Viewcontroller2.m)