I’m implementing a button class in cocos2d, and I want to be able to pass the selector when the button is created. Here is Button.m:
#import "CCButton.h"
@implementation CCButton
+(CCButton*) buttonFromImage:(NSString*)image selectedImage:(NSString*)selectedImage atPosition:(CGPoint)position selector:(SEL)selector_method
{
CCMenuItem *menuitem = [CCMenuItemImage itemFromNormalImage:image selectedImage:selectedImage target:self selector:selector_method];
menuitem.position = position;
CCButton *menu = [CCMenu menuWithItems:menuitem, nil];
menu.position = CGPointZero;
return menu;
}
@end
It inherits from CCMenu. What I want to do is define the selector method wherever create my button. For example, if I have a menu, I want the selector to be in the menu, and assign the selector to the button (in menu.m):
backButton = [CCButton buttonFromImage:@"image1.png" selectedImage:@"image2.png" atPosition:ccp(120,70) selector:@selector(backTouched:)];
[self addChild:backButton z:1];
...
- (void)backTouched:(id)sender {
//do what i want the button to do here
}
This crashes when I touch the button. How do I implement what I want?
Thanks for the help,
Dave
Edit: the error I get is bad pointer, SIGABRT
The target cannot be self. The target has to be the class that implements the button you have created.
When passing in the selector as you create the button, also pass in the target of the button creating class.
In other words, target is the class that contains the method that you pass as the selector.
Hope that made things clear 🙂
PS: Here’s what you should try. Note that your buttonFromImage now takes in a target attribute which is set when you create the backbutton. Also the target that you set in your buttonFromImage is not self, but the target that comes in from the buttonFromImage method.