将int传递给新的ViewController

时间:2012-06-25 23:03:11

标签: iphone objective-c ios xcode int

我花了一个月的时间尝试将我的int传递给新视图。我的int称为得分,并连接到一个名为scorelab的标签。用户增加得分并且一旦他们用完时游戏将视图切换到屏幕上的游戏,并且我希望用户得分在标签上在屏幕上显示在游戏上。游戏控制器被称为GamePlayViewController,被控制器称为GameDidEndViewController。我已经厌倦了试图让它发挥作用。我已经查看了每个可能的教程,但似乎没有什么能适用于我的情况。请帮助我,我会非常感激,这是我需要完成的游戏的最后一部分。提前谢谢!

对不起,这是代码:

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];  
}

2 个答案:

答案 0 :(得分:4)

您所做的是在GameDidEndViewController中创建一个属性,以保存传入的score值。

@interface GameDidEndViewController : UIViewController {

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

确保@synthesize score(。m)中的@implementation

现在,当您初始化并显示GameDidEndViewController时,您可以设置分数,可能是这样的。

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

希望这有帮助!

答案 1 :(得分:2)

以下是使用ViewControllers

Storyboard之间传递数据的一些教程
  1. Storyboards Segue Tutorial: Pass Data Between View Controllers
  2. Tutorial on How-To Pass Data Between Two View Controllers
  3. 或使用类似的东西:

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

    希望这有帮助。