Подтвердить что ты не робот

Как фиксировать жест Tap на MKMapView

Я пытаюсь захватить событие tap на моем MKMapView, таким образом я могу сбросить MKPinAnnotation в точке, где пользователь постучал. В основном у меня есть карта, наложенная на MKOverlayViews (наложение, показывающее здание), и я хотел бы предоставить пользователю дополнительную информацию об этом Overlay, когда они нажимают на него, отбрасывая MKPinAnnotaion и отображая больше информации в выноске. Спасибо.

4b9b3361

Ответ 1

Вы можете использовать UIGestureRecognizer для обнаружения касаний на карте.

Вместо однократного нажатия, я бы предложил искать двойной кран (UITapGestureRecognizer) или длительное нажатие (UILongPressGestureRecognizer). Один щелчок может помешать пользователю попытаться щелкнуть на самом выводе или выноске.

В том месте, где вы настраиваете вид карты (например, в viewDidLoad), присоедините распознаватель жестов к виду карты:

UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] 
    initWithTarget:self action:@selector(handleGesture:)];
tgr.numberOfTapsRequired = 2;
tgr.numberOfTouchesRequired = 1;
[mapView addGestureRecognizer:tgr];
[tgr release];

или использовать длительное нажатие:

UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] 
    initWithTarget:self action:@selector(handleGesture:)];
lpgr.minimumPressDuration = 2.0;  //user must press for 2 seconds
[mapView addGestureRecognizer:lpgr];
[lpgr release];


В методе handleGesture::

- (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer
{
    if (gestureRecognizer.state != UIGestureRecognizerStateEnded)
        return;

    CGPoint touchPoint = [gestureRecognizer locationInView:mapView];
    CLLocationCoordinate2D touchMapCoordinate = 
        [mapView convertPoint:touchPoint toCoordinateFromView:mapView];

    MKPointAnnotation *pa = [[MKPointAnnotation alloc] init];
    pa.coordinate = touchMapCoordinate;
    pa.title = @"Hello";
    [mapView addAnnotation:pa];
    [pa release];
}

Ответ 2

Я устанавливаю длинное нажатие (UILongPressGestureRecognizer) в viewDidLoad:, но он просто обнаруживает только одно касание от первого.

Где можно настроить длительное нажатие, чтобы обнаружить все касание? (это означает, что карта готова каждый раз, когда пользователь ждет сенсорный экран, чтобы нажать на контакт)

Метод viewDidLoad:!

- (void)viewDidLoad {
    [super viewDidLoad];mapView.mapType = MKMapTypeStandard;

    UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressGesture:)];
    [self.mapView addGestureRecognizer:longPressGesture];
    [longPressGesture release];

    mapAnnotations = [[NSMutableArray alloc] init];
    MyLocation *location = [[MyLocation alloc] init];
    [mapAnnotations addObject:location];

    [self gotoLocation];
    [self.mapView addAnnotations:self.mapAnnotations];
}

и handleLongPressGesture:

-(void)handleLongPressGesture:(UIGestureRecognizer*)sender {
    // This is important if you only want to receive one tap and hold event
    if (sender.state == UIGestureRecognizerStateEnded)
    {NSLog(@"Released!");
        [self.mapView removeGestureRecognizer:sender];
    }
    else
    {
        // Here we get the CGPoint for the touch and convert it to latitude and longitude coordinates to display on the map
        CGPoint point = [sender locationInView:self.mapView];
        CLLocationCoordinate2D locCoord = [self.mapView convertPoint:point toCoordinateFromView:self.mapView];
        // Then all you have to do is create the annotation and add it to the map
        MyLocation *dropPin = [[MyLocation alloc] init];
        dropPin.latitude = [NSNumber numberWithDouble:locCoord.latitude];
        dropPin.longitude = [NSNumber numberWithDouble:locCoord.longitude];
//        [self.mapView addAnnotation:dropPin];
        [mapAnnotations addObject:dropPin];
        [dropPin release];
        NSLog(@"Hold!!");
        NSLog(@"Count: %d", [mapAnnotations count]);
    }   
}

Ответ 3

Если вы хотите использовать один клик/коснуться на экране карты, вот фрагмент кода, который я использую. (Cocoa и Swift)

let gr = NSClickGestureRecognizer(target: self, action: "createPoint:")
gr.numberOfClicksRequired = 1
gr.delaysPrimaryMouseButtonEvents = false // allows +/- button press
gr.delegate = self
map.addGestureRecognizer(gr)

в методе делегата жестов, простой тест, чтобы предпочесть жест двойного касания...

func gestureRecognizer(gestureRecognizer: NSGestureRecognizer, shouldRequireFailureOfGestureRecognizer otherGestureRecognizer: NSGestureRecognizer) -> Bool {
  let other = otherGestureRecognizer as? NSClickGestureRecognizer
  if (other?.numberOfClicksRequired > 1) {
    return true; // allows double click
  }

  return false
}

вы также можете отфильтровать жест в других методах делегатов, если хотите, чтобы карта находилась в разных состояниях, одна из которых позволяла одному нажатию/щелчку