How to get a CGPoint from a tapped location?

后端 未结 6 1600
青春惊慌失措
青春惊慌失措 2020-12-01 06:32

I\'m working on a graphing calculator app for the iPad, and I wanted to add a feature where a user can tap an area in the graph view to make a text box pop up displaying the

6条回答
  •  广开言路
    2020-12-01 07:05

    it's probably better and simpler to use a UIGestureRecognizer with the map view instead of trying to subclass it and intercepting touches manually.

    Step 1 : First, add the gesture recognizer to the map view:

     UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] 
        initWithTarget:self action:@selector(tapGestureHandler:)];
     tgr.delegate = self;  //also add  to @interface
     [mapView addGestureRecognizer:tgr];
    

    Step 2 : Next, implement shouldRecognizeSimultaneouslyWithGestureRecognizer and return YES so your tap gesture recognizer can work at the same time as the map's (otherwise taps on pins won't get handled automatically by the map):

    - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer 
    shouldRecognizeSimultaneouslyWithGestureRecognizer
        :(UIGestureRecognizer *)otherGestureRecognizer
    {
       return YES;
    }
    

    Step 3 : Finally, implement the gesture handler:

    - (void)tapGestureHandler:(UITapGestureRecognizer *)tgr
    {
       CGPoint touchPoint = [tgr locationInView:mapView];
    
       CLLocationCoordinate2D touchMapCoordinate 
        = [mapView convertPoint:touchPoint toCoordinateFromView:mapView];
    
       NSLog(@"tapGestureHandler: touchMapCoordinate = %f,%f", 
        touchMapCoordinate.latitude, touchMapCoordinate.longitude);
    }
    

提交回复
热议问题