Reputation: 157
Ive spent a month trying to pass my int to a new view. My int is called score and is connected to a label called scorelab. The user increases the score and once the they run out of time game switches views to game over screen and i would like the users score to be displayed on the game over screen in a label. The game play controller is called GamePlayViewController
and the gave over controller is called GameDidEndViewController
. I'm tired of trying to get this to work. I have looked at every tutorial possible but nothing seems to work for my case. Please help me i would appreciate it so so much, this is the very last part of game that I need to finish. Thank you in advance!
Sorry here is the code:
GamePlayViewController.h
#import "GameDidEndViewController.h"
int score;
IBOutlet UILabel *scorelab;
GamePlayViewController.m
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"GameOver"])
{
GameDidEndViewController *vc = [segue destinationViewController];
[vc setscore2: score];
}
}
GameDidEndViewController.h
#import "GamePlayViewController.h"
IBOutlet UILabel *scorelab2;
int score2;
}
@property (nonatomic , assign) int score2;
@property (nonatomic , assign) UILabel *scorelab2;
GameDidEndViewController.m
@synthesize score2 , scorelab2;
-(void)viewWillAppear:(BOOL)animated {
scorelab2.text = [NSString stringWithFormat: @"%d", score2];
[super viewWillAppear: animated];
}
Upvotes: 0
Views: 2357
Reputation: 2466
Here is some tutorial for passing data between ViewControllers
using Storyboard
:
or use something like this:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:...]) {
MyViewController *controller = (MyViewController *)segue.destinationViewController;
controller.score = score;
}
}
Hope this helps.
Upvotes: 2
Reputation: 5314
What you do is create a property in GameDidEndViewController
to hold the passed in score
value.
@interface GameDidEndViewController : UIViewController {
....
}
@property(nonatomic,assign) int score;
@end
Make sure you @synthesize score
in the @implementation
(.m).
Now when you init and show the GameDidEndViewController
you set the score, likely something like this.
GameDidEndViewController *end = .....// init the view.
end.score = score; // assuming you're doing this from GamePlayViewController where it has an int named `score`
Hope this helps !
Upvotes: 4