Search code examples
iosxcodeviewuitouch

IOS, Xcode: capture UITouch event ended


I am a beginner in IOS programming...I am not familiar with the methods at this moment. The setting is: I have a function called. In this function, I would like to wait for one tap and then generate a new ViewController. I only need the CGPoint of tap and then move on to the next steps. But I don't know if there is some method which could capture touchesEnded. Or maybe I think in the wrong way. Could anyone provide me some ?

If I create the new viewController just after the touch ended, then nothing is happen after the modelDetect(it's required). The application will end before get a touch.

So I have no idea now.

Really thanks a lot.

- (void)modelDetect
{
 //wait for touches....then
 [self addNewViewController]; 
}


- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event  
{
   NSLog(@"touch happens");
   UITouch *touch = [touches anyObject];
   Location = [touch locationInView:self.view];      
}

Solution

  • You could try using UITapGestureRecognizer it could solve your issue

    UITapGestureRecognizer *rec = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(userTapped:)];
    [self addGestureRecognizer:rec];
    
    
    - (void)userTapped:(UITapGestureRecognizer *)recognizer
    {
        if(recognizer.state == UIGestureRecognizerStateRecognized)
        {
            CGPoint point = [recognizer locationInView:recognizer.view]; 
            // point.x and point.y  touch coordinates
             NSLog("%lf %lf", point.x, point.y);
    
            // here you could call your method or add the new view controller which you want
             [self addNewViewController]; 
        }
    }
    

    For getting the point through touchesEnded you should use CGPoint

    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
    {
        UITouch *aTouch = [touches anyObject];
        CGPoint point = [aTouch locationInView:self];
        // point.x and point.y touch coordinates
        NSLog("%lf %lf", point.x, point.y);
    }