John Farkerson
John Farkerson

Reputation: 2632

Draggable image from class file

I understand how to make a draggable image, but I am having trouble making an image from a class file be draggable from my main ViewController.m file. My class is called "bomb". Every two seconds, a new bomb is created, and with it a bombImage (an object of bomb). The bomb is added to an NSMutableArray (bombArray).

- (void) newBomb
{
    bomb *bomb1 = [[bomb alloc] init];
    [bombArray addObject: bomb1];
    [bomb1 displayBombOnView:self.view]; //displayBombOnView just makes a new bomb in a random location
}

I am trying to make it so that the user can drag each "bomb" around.

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event : (bomb *) bomb
{
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:touch.view];
    bomb->bombImage.center = location;
}

-(void) touchesMoved:(NSSet*)touches withEvent:(UIEvent *)event
{
    bomb *tempBomb  = [[bomb alloc] init];
    arrayCount = [bombArray count];
    for (int k = 0; k<arrayCount; k++)
    {
        tempBomb = [bombArray objectAtIndex:k];
        CGPoint tappedPt = [[touches anyObject] locationInView: self];
        int     xPos = tappedPt.x;
        int     yPos = tappedPt.y;
        if ((xPos >= tempBomb->bombImage.center.x - 25 && xPos <= tempBomb->bombImage.center.x + 25) && (yPos >= tempBomb->bombImage.center.y - 25 && xPos <= tempBomb->bombImage.center.y + 25))
        {
            [self touchesBegan:touches withEvent:event : [bombArray objectAtIndex:k]];
            break;
        }
    }
}

It builds, but then when I try to drag the image, it crashes, saying Thread 1: signal SIGABRT. Any help would be greatly appreciated.

Upvotes: 0

Views: 96

Answers (1)

Wain
Wain

Reputation: 119021

Instead of what you're doing, use a UIPanGestureRecognizer. Add a recognizer to each bomb image view when you create it and then when the gesture recognizer calls your action method you can directly access the view and use the recognizer position to move the view.

Upvotes: 2

Related Questions