Question

I want to create and see a uiimageview when i tap the screen. Before i lift the finger, i want to move the uiimageview around the screen and the image set only when i take the finger off. Heres what i did:

- (IBAction)tap:(UITapGestureRecognizer *)recognizer {

    CGPoint location = [recognizer locationInView:self.view];

    UIImageView *circle = [[UIImageView alloc] initWithFrame:CGRectMake(location.x, location.y, 50, 50)];
    circle.userInteractionEnabled = YES;
    [circle setImage:[UIImage imageNamed:@"monkey_1.png"]];
    [self.view addSubview:circle];

    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:circle action:nil];
    [recognizer requireGestureRecognizerToFail:pan];

    CGPoint translation = [pan translationInView:circle];
    pan.view.center = CGPointMake(pan.view.center.x + translation.x, pan.view.center.y + translation.y);
    [pan setTranslation:CGPointMake(0, 0) inView:self.view];
}
Was it helpful?

Solution

You can do this with just an UIPanGestureRecognizer or an UILongPressGestureRecognizer. In the gesture handling method, check the state property of the recognizer, and show your image when it's UIGestureRecognizerStateEnded (i.e. when the user lifts the finger from the screen). E.g.:

- (void)handleGesture:(UILongPressGestureRecognizer *)recognizer {
    if(recognizer.state == UIGestureRecognizerStateEnded) {
       // gesture ended: show the image
    }
    else if(recognizerState == UIGestureRecognizerStateBegan) {
        // this code runs when the gesture is started. 
    }
    else if(recognizerState == UIGestureRecognizerStateChanged) {
        // gesture is in progress
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top