2012-06-25 26 views
0

我花了一个月试图将我的int传递给一个新的视图。我的int被称为score,并连接到一个名为scorelab的标签。用户增加分数,一旦他们用完时间游戏将视图切换到屏幕上的游戏,并且我希望用户分数在标签中的屏幕上显示在游戏上。游戏控制器被称为GamePlayViewController,并且控制器被给予为GameDidEndViewController。我厌倦了试图让这个工作。我已经看过每一个可能的教程,但似乎没有任何工作适合我的情况。请帮助我,我会很感激,这是我需要完成的最后一部分游戏。先谢谢你!将一个int传递给一个新的ViewController

对不起这里是代码:

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; 

耍花招idEndViewController.m

@synthesize score2 , scorelab2; 
-(void)viewWillAppear:(BOOL)animated { 
scorelab2.text = [NSString stringWithFormat: @"%d", score2]; 
[super viewWillAppear: animated]; 
} 
+2

你有什么试过?如果你一直在尝试一个月,那肯定意味着你有一些不起作用的代码。我们在这里告诉你为什么它不起作用,不是为你做。 –

回答

2

下面是使用StoryboardViewControllers之间传递数据的一些教程:

  1. Storyboards Segue Tutorial: Pass Data Between View Controllers
  2. Tutorial on How-To Pass Data Between Two View Controllers

或使用这样的:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
    if ([segue.identifier isEqualToString:...]) { 
     MyViewController *controller = (MyViewController *)segue.destinationViewController; 
     controller.score = score; 
    } 
} 

希望这有助于。

+0

非常感谢你!!!!!!它完美的工作! –

+0

这对于人们在他们的.m文件中添加对象和属性变得很常见。所以,如果你得到一个错误,其中controller.score = score;请确保在您的目标视图控制器中您声明您的.h文件中的整数而不是.m文件中。那么你的错误将消失。 –

4

你要做的就是在GameDidEndViewController创建属性持有score值传递。

@interface GameDidEndViewController : UIViewController { 

.... 
} 
@property(nonatomic,assign) int score; 
@end 

确保您在@implementation(.M)@synthesize score

现在,当您初始化并显示GameDidEndViewController时,您可以设置得分,可能类似于此。

GameDidEndViewController *end = .....// init the view. 
end.score = score; // assuming you're doing this from GamePlayViewController where it has an int named `score` 

希望这会有所帮助!

+0

我不认为这是故事板...应该提到我需要它的故事板 –

相关问题