aijuans2 发表于 2013-1-30 20:26:25

cocos2d子层访问父层的三种方法

情景设定:父层HelloWorldLayer有一个方法-(void) setlable;需要被其子层SecondLayer访问。

第一种、半单例方法:
首先在HelloWorldLayer.h声明+(HelloWorldLayer*) shareLayer

+(HelloWorldLayer*) shareLayer;
然后在HelloWorldLayer.m加入:

#import "SecondLayer.h"static HelloWorldLayer* HelloWorldLayerInstance;+(HelloWorldLayer*) shareLayer{    return HelloWorldLayerInstance;}-(id) init{    // always call "super" init    // Apple recommends to re-assign "self" with the "super" return value    if( (self=)) {        HelloWorldLayerInstance=self;                SecondLayer* sl=[ init];        sl.tag=10;        ;        self.isTouchEnabled=YES;                ////.................           }    return self;}-(void) setlable{    clickNum++;    ];}
在SecondLayer就可以通过这样的方式来访问HelloWorldLayer的-(void) setlable方法:

[ setlable];
第二种、self.parent强制访问方法:
HelloWorldLayer中只需按正常添加子层SecondLayer即可(HelloWorldLayer.m中):

-(id) init{    // always call "super" init    // Apple recommends to re-assign "self" with the "super" return value    if( (self=)) {      HelloWorldLayerInstance=self;                SecondLayer* sl=[ init];      sl.tag=10;      ;      self.isTouchEnabled=YES;                ////.................         }    return self;}
在SecondLayer就可以通过这样的方式来访问HelloWorldLayer的-(void) setlable方法:

[(HelloWorldLayer*)self.parent setlable];
第三种、协议委托方法:
在SecondLayer.h中加入:

#import <Foundation/Foundation.h>#import "cocos2d.h"@protocol callParentDelegate <NSObject>-(void) setlable;@end@interface SecondLayer : CCLayer{    id<callParentDelegate> delegate;}@property(nonatomic,retain) id<callParentDelegate> delegate;@endSecondLayer.m中@synthesize delegate;
然后在HelloWorldLayer.h中加入<callParentDelegate>协议:

@interface HelloWorldLayer :CCLayer <callParentDelegate>{    CCLabelTTF *label;    int clickNum;}
在HelloWorldLayer.m中实现:

-(void) setlable{    clickNum++;    ];}
在添加SecondLayer子层注意设子委托:

         SecondLayer* sl=[ init];      sl.tag=10;      sl.delegate=self;      ;      self.isTouchEnabled=YES;
在SecondLayer就可以通过这样的方式来访问HelloWorldLayer的-(void) setlable方法:

;
还有更好的办法,欢迎各位交流!
页: [1]
查看完整版本: cocos2d子层访问父层的三种方法