iPhone: Detecting Tap in MKMapView

后端 未结 8 1396
天命终不由人
天命终不由人 2020-12-24 07:35

How do I detect a single tap on an instance of MKMapView? Do I have to subclass MKMapView and then override the touchesEnded method?

相关标签:
8条回答
  • 2020-12-24 08:06

    my 2 cents for swit 5.x:

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let v = touch.view
            let ssv = v?.superview?.superview
            if ssv === self.mapView{
                searchBar.resignFirstResponder()
            }
        }
    }
    

    it works. but honestly can break if apple changes layers of views. better a recognizer.

    0 讨论(0)
  • 2020-12-24 08:09

    Just add some code snippet as illustration of @tt-kilew answer. In my case, I want to point the user to itself on the map but do not want to interrupt his drag touch.

    @interface PrettyViewController () <MKMapViewDelegate>
    
    @property (weak, nonatomic) IBOutlet MKMapView *mapView;
    @property (assign, nonatomic) BOOL userTouchTheMap;
    
    @end
    
    @implementation PrettyViewController
    
    #pragma mark - UIResponder
    
    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
        [super touchesBegan:touches withEvent:event];
    
        self.userTouchTheMap = [[touches anyObject].view isEqual:self.mapView];
    }
    
    
    #pragma mark - MKMapViewDelegate
    
    - (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
        //We just positioning to user
        if (!self.userTouchTheMap) {
            CLLocationDistance radius = 5000;
            [self.mapView setRegion:MKCoordinateRegionMakeWithDistance(userLocation.location.coordinate, 2*radius, 2*radius) animated:YES];
        }
    }
    
    @end
    
    0 讨论(0)
提交回复
热议问题