this Obj-C stuff can be confusing at first. Hopefully this will help.
I notice two things for you to change.
The first is in regards to your TAP
gesture. When you add this to your code you're actually telling the gesture to recognize a TAP and then run the tapped
method. However, this method doesn't exist (hence the -[C4Shape tapped]: unrecognized selector sent to instance 0x931e9c0
). You should have a method in your code called -(void)tapped{};
for this message to go away.
The following code illustrates this:
@implementation C4WorkSpace
-(void)setup {
[self addGesture:TAP name:@"tap" action:@"tapped"];
}
-(void)tapped {
C4Log(@"tapped!");
}
@end
Putting that into a shape is quite similar.
Second, for the subclassing, C4Shape (and all other visual objects) inherit from C4Control so I would suggest that subclassing C4Control isn't the best approach. For creating your own custom button with a C4Shape I would subclass C4Shape directly.
The above code would look exactly the same for a subclassed C4Shape except that if you created a MyShape subclass would have @implementation MyShape
instead.
Finally, you want to add a little broadcast message to your tap
method so that the canvas can listen for it... All in all your .h
and .m
files for your subclass should look like this:
.h
#import "C4Shape.h"
@interface MyShape : C4Shape
@end
.m
#import "MyShape.h"
@implementation MyShape
-(void)setup {
[self addGesture:TAP name:@"tap" action:@"tapped"];
}
-(void)tapped {
[self postNotification:@"tapNotification"];
}
@end
Finally, with those two files in your project you can add the following to your workspace:
#import "C4WorkSpace.h"
#import "MyShape.h"
@implementation C4WorkSpace
-(void)setup {
MyShape *m = [[MyShape alloc] init];
[m rect:CGRectMake(0, 0, 100, 100)];
m.center = self.canvas.center;
[self.canvas addShape:m];
[self listenFor:@"tapNotification" fromObject:m andRunMethod:@"heardTap:"];
}
-(void)heardTap:(NSNotification *)aNotification {
MyShape *notificationShape = (MyShape *)[aNotification object];
C4Log(@"%4.2f,%4.2f",notificationShape.center.x,notificationShape.center.y);
C4Log(@"%@",notificationShape.strokeColor);
}
@end
Here's a link to a gist with the 3 files you'll need for this to run.
Button Subclass with Canvas Listener
PS thanks for giving C4 a try!
Oh, and this is the output I get in Xcode's console when I tap on the square:
[C4Log] 384.00,512.00
[C4Log] UIDeviceRGBColorSpace 1 0.1 0.1 1
This gives me the x
and y
coordinates, as well as the strokeColor
of the "button" without having to add these as objects to the MyShape
class (because they already exist in C4Shape
).