在数据传递过程中,我们创建一个delegate进行辅助:

helpDelegate.h文件

#import <Foundation/Foundation.h>

@protocol helpDelegate

- (void)passValue:(NSString*)value;

@end

helpDelegate.m里面都可以不用写内容

接下来我们看下需要进行数据传递的2个类:

第一个类:

HelloWorldLayer.h文件

#import "cocos2d.h"

#import "helpDelegate.h"

@interface HelloWorldLayer : CCLayer<helpDelegate> { }

+(CCScene *) scene;

@end

HelloWorldLayer.m文件

#import "HelloWorldLayer.h"

#import "SubLayer.h"

#import "cocos2d.h"

#import "CCTransition.h"

@implementation HelloWorldLayer

+(CCScene *) scene

{  

CCScene *scene = [CCScene node];

 HelloWorldLayer *layer = [HelloWorldLayer node];

 [scene addChild: layer];  

return scene;

}

-(id) init

{    

  if( (self=[super init]))

  {        

    CGSize size = [[CCDirector sharedDirector] winSize];        

    CCMenuItem *InsMn = [CCMenuItemFont itemFromString:@"Next" target:self selector:@selector(OnInstantAction:)];        

    CCMenu *menus = [CCMenu menuWithItems:InsMn, nil];        

     [self addChild:menus];  

  }  

  return self;

}

- (void) OnInstantAction:(id) sender {        

  CCScene *sc = [CCScene node];    

   SubLayer *subLayer = [SubLayer node];    

  subLayer.delegate=self;    

   [sc addChild:subLayer];    

   [[CCDirector sharedDirector] replaceScene: [CCTransitionSlideInR transitionWithDuration:1.2f scene:sc]];

}

-(void)passValue:(NSString *)value {    

  CGSize size = [[CCDirector sharedDirector] winSize];    

  CCLabelTTF *label = [CCLabelTTF labelWithString:value fontName:@"Marker Felt" fontSize:64];    

  label.position = ccp(size.width/2, size.height/2+30);    

  [self addChild:label];   

}

- (void) dealloc {  [super dealloc]; }

@end

第二个类:

SubLayer.h文件

#import <Foundation/Foundation.h>

#import "cocos2d.h" #import "helpDelegate.h"

@interface SubLayer : CCLayer {     }

@property (nonatomic,retain) CCLayer<helpDelegate>* delegate;

@end

SubLayer.m文件

#import "SubLayer.h" #import "HelloWorldLayer.h"

@implementation SubLayer

@synthesize delegate;

+(CCScene *) scene {

   CCScene *scene = [CCScene node];

   SubLayer *layer = [SubLayer node];  

  [scene addChild: layer];  return scene;

}

-(id) init {  

  if( (self=[super init])) {     

     CCMenuItem *InsMn = [CCMenuItemFont itemFromString:@"Previous" target:self selector:@selector(OnInstantAction:)];        

     CCMenu *menus = [CCMenu menuWithItems:InsMn, nil];        

     [self addChild:menus];  

  }

   return self;

}

- (void) OnInstantAction:(id) sender {    

   CCScene *sc = [CCScene node];    

   [delegate passValue:@"haha"]; //将字符串传递给HelloWorldLayer   

  [sc addChild:delegate];    

  [[CCDirector sharedDirector] replaceScene: [CCTransitionSlideInR transitionWithDuration:1.2f scene:sc]];

}

@end

 

posted on 2013-03-03 09:45  aparche  阅读(1995)  评论(0编辑  收藏  举报