【问题标题】:iOS MapView: Add Annotation on tap, but not if existing Annotation TappediOS MapView:点击时添加注释,但如果现有注释被点击则不添加
【发布时间】:2014-02-05 22:09:55
【问题描述】:

我有一个 UITapGestureRecognizer 设置来在用户单击的地图上添加注释。我遇到的问题是当用户点击现有注释以查看工具提示时,工具提示会弹出,但另一个注释会添加到单击的注释后面的地图中。有没有办法在添加注释之前检测注释是否被点击并返回?

这是我的 viewDidLoad:

UITapGestureRecognizer *singleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(foundTap:)];
singleTapRecognizer.numberOfTapsRequired = 1;
[self.mapView addGestureRecognizer:singleTapRecognizer];

还有我的触控功能:

-(IBAction)foundTap:(UITapGestureRecognizer *)recognizer
{
    CGPoint point = [recognizer locationInView:self.mapView];

    CLLocationCoordinate2D tapPoint = [self.mapView convertPoint:point toCoordinateFromView:self.view];

    AGIAnnotation * annotation = [[AGIAnnotation alloc] initWithCoordinate:tapPoint];
    // Some other stuff

    [self.mapView addAnnotation:annotation];
}

感谢任何帮助。

【问题讨论】:

  • 无关说明:在 convertPoint 调用中,您可能希望使用 toCoordinateFromView:self.mapView 而不是 self.viewself.view 仅在地图视图占据整个屏幕时才有效。如果您将地图视图更改为小于屏幕(特别是如果它的原点不是 0,0),您将返回错误的点。

标签: ios mkmapview mapkit mkannotation


【解决方案1】:

有一个UIGestureRecognizerDelegate Protocol

实现gestureRecognizer:shouldReceiveTouch:,如果触摸在现有工具提示上,则返回NO。像这样的:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([touch.view isKindOfClass:[MKPinAnnotationView class]])
    {
        return NO;
    }
    return YES;
}

【讨论】:

  • 太棒了,这正是我所需要的。我必须做的唯一更改是将 isKindOfClass 更改为 MKPinAnnotaionView。谢谢
  • 手势代表未调用
【解决方案2】:

@mbehan 在 Swift 3+ 中回答:

在 ViewDidLoad 中:

let singleTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(YourClass.foundTap(_:)))
singleTapRecognizer.delegate = self
mapView.addGestureRecognizer(singleTapRecognizer)

和 UIGestureRecognizerDelegate 扩展:

extension YourClass: UIGestureRecognizerDelegate {
  func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
    return !(touch.view is MKPinAnnotationView)
  }
}

【讨论】:

  • 寻找一个与我的设置相匹配的答案,但在看到这个之前找不到任何东西!
  • 这个解决方案很棒,但是如果你的 mapview 中有很多 pin,比如超过 50 个,那么结果 = !(touch.view is MKPinAnnotationView) 的运行需要永远
  • 哦,这很奇怪!上面的代码显然没有贯穿所有引脚。也许归档雷达?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-26
  • 1970-01-01
相关资源
最近更新 更多