How to get a CGPoint from a tapped location? How to get a CGPoint from a tapped location? ios ios

How to get a CGPoint from a tapped location?

you have two way ...


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

here,you can get location with point from current view...


UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)];[tapRecognizer setNumberOfTapsRequired:1];[tapRecognizer setDelegate:self];[self.view addGestureRecognizer:tapRecognizer];

here,this code use when you want to do somthing with your perticular object or subview of your mainview

Try This

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {  UITouch *touch = [touches anyObject];  // Get the specific point that was touched  CGPoint point = [touch locationInView:self.view];   NSLog(@"X location: %f", point.x);  NSLog(@"Y Location: %f",point.y);}

You can use "touchesEnded" if you'd rather see where the user lifted their finger off the screen instead of where they touched down.

Just want to toss in a Swift 4 answer because the API is quite different looking.

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {    if let touch = event?.allTouches?.first {        let loc:CGPoint = touch.location(in: touch.view)        //insert your touch based code here    }}


let tapGR = UITapGestureRecognizer(target: self, action: #selector(tapped))view.addGestureRecognizer(tapGR)@objc func tapped(gr:UITapGestureRecognizer) {    let loc:CGPoint = gr.location(in: gr.view)      //insert your touch based code here}

In both cases loc will contain the point that was touched in the view.