歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> cocos2d子層訪問父層的三種方法

cocos2d子層訪問父層的三種方法

日期:2017/3/1 10:13:16   编辑:Linux編程

情景設定:父層HelloWorldLayer有一個方法-(void) setlable;需要被其子層SecondLayer訪問。

第一種、半單例方法:

首先在HelloWorldLayer.h聲明+(HelloWorldLayer*) shareLayer

  1. +(HelloWorldLayer*) shareLayer;

然後在HelloWorldLayer.m加入:

  1. #import "SecondLayer.h"
  2. static HelloWorldLayer* HelloWorldLayerInstance;
  3. +(HelloWorldLayer*) shareLayer
  4. {
  5. return HelloWorldLayerInstance;
  6. }
  7. -(id) init
  8. {
  9. // always call "super" init
  10. // Apple recommends to re-assign "self" with the "super" return value
  11. if( (self=[super init])) {
  12. HelloWorldLayerInstance=self;
  13. SecondLayer* sl=[[SecondLayer alloc] init];
  14. sl.tag=10;
  15. [self addChild:sl z:100];
  16. self.isTouchEnabled=YES;
  17. ////.................
  18. }
  19. return self;
  20. }
  21. -(void) setlable
  22. {
  23. clickNum++;
  24. [label setString:[NSString stringWithFormat:@"ParentLayer clickNum:%i",clickNum]];
  25. }

在SecondLayer就可以通過這樣的方式來訪問HelloWorldLayer的-(void) setlable方法:

  1. [[HelloWorldLayer shareLayer] setlable];

第二種、self.parent強制訪問方法:

HelloWorldLayer中只需按正常添加子層SecondLayer即可(HelloWorldLayer.m中):

  1. -(id) init
  2. {
  3. // always call "super" init
  4. // Apple recommends to re-assign "self" with the "super" return value
  5. if( (self=[super initWithColor:ccc4(0, 255, 255,255)])) {
  6. HelloWorldLayerInstance=self;
  7. SecondLayer* sl=[[SecondLayer alloc] init];
  8. sl.tag=10;
  9. [self addChild:sl z:100];
  10. self.isTouchEnabled=YES;
  11. ////.................
  12. }
  13. return self;
  14. }
在SecondLayer就可以通過這樣的方式來訪問HelloWorldLayer的-(void) setlable方法:
  1. [(HelloWorldLayer*)self.parent setlable];
第三種、協議委托方法:

在SecondLayer.h中加入:

  1. #import <Foundation/Foundation.h>
  2. #import "cocos2d.h"
  3. @protocol callParentDelegate <NSObject>
  4. -(void) setlable;
  5. @end
  6. @interface SecondLayer : CCLayer{
  7. id<callParentDelegate> delegate;
  8. }
  9. @property(nonatomic,retain) id<callParentDelegate> delegate;
  10. @end
SecondLayer.m中@synthesize delegate;

然後在HelloWorldLayer.h中加入<callParentDelegate>協議:

  1. @interface HelloWorldLayer :CCLayer <callParentDelegate>
  2. {
  3. CCLabelTTF *label;
  4. int clickNum;
  5. }

在HelloWorldLayer.m中實現:

  1. -(void) setlable
  2. {
  3. clickNum++;
  4. [label setString:[NSString stringWithFormat:@"ParentLayer clickNum:%i",clickNum]];
  5. }

在添加SecondLayer子層注意設子委托:

  1. SecondLayer* sl=[[SecondLayer alloc] init];
  2. sl.tag=10;
  3. sl.delegate=self;
  4. [self addChild:sl z:100];
  5. self.isTouchEnabled=YES;
在SecondLayer就可以通過這樣的方式來訪問HelloWorldLayer的-(void) setlable方法:
  1. [self.delegate setlable];

還有更好的辦法,歡迎各位交流!

Copyright © Linux教程網 All Rights Reserved