【问题标题】:Passing an int to a new ViewController将 int 传递给新的 ViewController
【发布时间】:2012-06-25 23:03:11
【问题描述】:

我花了一个月的时间试图将我的 int 传递给一个新的视图。我的 int 称为 score 并连接到一个名为 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];  
}

【问题讨论】:

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

标签: iphone objective-c ios xcode int


【解决方案1】:

您要做的是在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`

希望这会有所帮助!

【讨论】:

  • 我不认为这是用于故事板的...应该提到我需要它用于故事板
【解决方案2】:

这里有一些使用Storyboard在ViewControllers之间传递数据的教程:

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

希望这会有所帮助。

【讨论】:

  • 人们在他们的 .m 文件中添加对象和属性已成为惯例。因此,如果您遇到错误 where controller.score = score;确保在目标视图控制器中,您在 .h 文件中而不是在 .m 文件中声明整数。然后你的错误就会消失。
猜你喜欢
  • 2016-02-04
  • 2015-04-03
  • 1970-01-01
  • 1970-01-01
  • 2018-03-21
  • 1970-01-01
  • 1970-01-01
  • 2011-08-17
  • 2010-12-11
相关资源
最近更新 更多