Search code examples
iossparrow-framework

Sparrow: How to have different events for touch and drag


Basically I want to touch a image to rotate it about the centre by 90 degrees. Drag the image to move it (without rotating).

- (void) onImageTouched:(SPTouchEvent *)event
{
    SPImage *img = (SPImage *)event.target;
    SPTouch *drag = [[event touchesWithTarget:self andPhase:SPTouchPhaseMoved] anyObject];
    SPTouch *touch = [[event touchesWithTarget:self andPhase:SPTouchPhaseBegan] anyObject];
    float offsetX, offsetY;
    if(touch){
        SPPoint *initial = [touch locationInSpace:self];
        offsetX = initial.x - img.x;
        offsetY = initial.y - img.y;
    }
    if (drag) {
        SPPoint *dragPosition = [drag locationInSpace:self];
        NSLog(@"Touched (%f %f)",dragPosition.x, dragPosition.y);
        //img.x = dragPosition.x - offsetX;
        //img.y = dragPosition.y - offsetY;

    }
    else{
        img.pivotX = img.width / 2.0f;
        img.pivotY = img.height / 2.0f;
        NSLog(@"Rotated aboout(%f %f)",img.pivotX,img.pivotY);
        //img.rotation = SP_D2R(90);
    }

}

Above is my code.

When I drag it, it does move but the image's position is quite far from my pointers. Also, at the start and end of dragging, the image rotates.

When I tap it, it disappears. (maybe move or rotate to somewhere outside the screen)

Any suggestions?


Solution

  • Ok I woould do something like this:

    - (void) onImageTouched:(SPTouchEvent *)event
    {
        SPImage *img = (SPImage *)event.target;
        SPTouch *drag = [[event touchesWithTarget:self andPhase:SPTouchPhaseMoved] anyObject];
        SPTouch *touch = [[event touchesWithTarget:self andPhase:SPTouchPhaseBegan] anyObject];
        SPTouch *endTouch = [[event touchesWithTarget:self andPhase:SPTouchPhaseEnded] anyObject];
        float offsetX, offsetY;    
        static BOOL dragging = NO;
        if(touch){
            dragging = NO;
        } else if (drag) {
            dragging = YES;
            SPPoint *dragPosition = [drag locationInSpace:self];
            NSLog(@"Touched (%f %f)",dragPosition.x, dragPosition.y);
            img.x = dragPosition.x;
            img.y = dragPosition.y;
        }
        else if (endTouch) {
            if (!dragging) {
                img.pivotX = img.width / 2.0f;
                img.pivotY = img.height / 2.0f;
                NSLog(@"Rotated aboout(%f %f)",img.pivotX,img.pivotY);
                img.rotation = SP_D2R(90);
            }
        }
    
    }
    

    This variant should solve the problem of the offset while dragging and the fact that when you drag it rotates anyway.

    Note the static variable in the method (dragging) it would be better if you put it as a private variable in the implementation (I just saved time by doing it this way ;) ).

    I haven't test this code but the idea should be clear (I hope).

    Regards