2012-06-25 60 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

我不認爲這是故事板...應該提到我需要它的故事板 –

相關問題