Search code examples
iosc4

Adding gestures to a shape - c4framework


I'm just learning how to use the C4 framework and trying to add gestures to a shape, but I can't seem to figure out how to get them to do anything. The following method creates an error, when I try to change the position of a button after it is tapped.

[buttonA addGesture:TAP name:@"tapGesture" action:@"setPosition"];

This is the error I get: * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MyButton setPosition]: unrecognized selector sent to instance 0x7661b60'


Solution

  • I'm guessing that the reason you're getting the error is because the setPosition method is because you're trying to run the setPosition method directly on a C4Shape object. Natively, C4Shapes don't have this method.

    In C4, all objects can have gestures attached to them, but in order run any custom code when you trigger a gesture on an object you should first subclass C4Shape and write a special method to handle the behaviour you want to see.

    For example, I would create a MyShape class like this:

    @interface MyShape : C4Shape
    -(void)setNewPosition;
    @end
    
    @implementation MyShape
    -(void)setNewPosition {
        //will set the center of the shape to a new random point
        self.center = CGPointMake([C4Math randomInt:768], [C4Math randomInt:1024]);
    }
    @end
    

    Then, in my C4WorkSpace:

    #import "C4WorkSpace.h"
    #import "MyShape.h"
    
    @implementation C4WorkSpace {
        MyShape *newShape;
    }
    -(void)setup {
        newShape = [MyShape new];
        [newShape ellipse:CGRectMake(100, 100, 200, 200)];
        [newShape addGesture:TAP name:@"tapGesture" action:@"setNewPosition"];
        [self.canvas addShape:newShape];
    }
    @end
    

    This should register a tap gesture with your new subclassed shape, and run its setNewPosition method when the gesture is triggered.