ios - 如何使 MKAnnotationView 触敏?

标签 ios iphone objective-c cocoa-touch

我目前有一个带有一些注释的 map View 。我有自定义图像的注释。我要解决的问题是图像的敏感性。当我尝试拖动它们时,感觉就像我必须触摸确切的中心才能使其聚焦。有没有办法让触摸边界变大?

最佳答案

为此,您需要子类化 MKAnnotationView 以创建您自己的自定义 MKAnnotationView。在您的子类中,重写以下函数:

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent*)event
{
    // Return YES if the point is inside an area you want to be touchable
}

- (UIView*)hitTest:(CGPoint)point withEvent:(UIEvent*)event
{
    // Return the deepest view that the point is inside of.
}

这允许按下交互式 View (例如按钮等)。 MKAnnotationView 中的默认实现对 pointInsidehitTest 并不严格,因为它允许实际上在一个注解内的按下被发送到不同的注解.它通过找出离触摸点最近的注释中心并将事件发送到该注释来实现这一点,这样靠近(重叠)的注释就不会互相阻止被选中。但是,在您的情况下,如果用户要选择并拖动最上面的注释,您可能希望阻止其他注释,因此上述方法可能是您想要的,否则它会让您走上正确的道路。

编辑: 我在评论中被问及 hitTest:withEvent: 的示例实现 - 这完全取决于您要实现的目标。最初的问题建议在注释中触摸和拖动图像,而在我的例子中,我在注释中有一些我想要交互的按钮。这是我的代码:

- (UIView*)hitTest:(CGPoint)point withEvent:(UIEvent*)event
{
    UIView* hitView = [super hitTest:point withEvent:event];
    if (hitView != nil)
    {
        // ensure that the callout appears above all other views
        [self.superview bringSubviewToFront:self];

        // we tapped inside the callout
        if (CGRectContainsPoint(self.resultView.callButton.frame, point))
        {
            hitView = self.resultView.callButton;
        }
        else if (CGRectContainsPoint(self.resultView.addButton.frame, point))
        {
            hitView = self.resultView.addButton;
        }
        else
        {
            hitView = self.resultView.viewDetailsButton;
        }
        [self preventSelectionChange];
    }
    return hitView;
}

如您所见,它非常简单 - MKAnnotationView 实现(在我的实现的第一行称为 super)仅返回第一个(最外层) View ,它不会向下钻取 View 层次结构以查看触摸实际位于哪个 subview 中。在我的例子中,我只是检查触摸是否在三个按钮之一内并返回它们。在其他情况下,您可能有简单的基于矩形的向下钻取层次结构或更复杂的 HitTest ,例如为了避免 View 中的透明区域以允许触摸通过这些部分。如果您确实需要向下钻取,CGRectContainsPoint 的使用方式与我使用它的方式相同,但请记住将您的点偏移到您钻取的每个 View 级别的局部 View 坐标中。

preventSelectionChange 方法是为了防止我的自定义注释被选中,我将其用作 map 图钉的可自定义/交互式标注,这会保留与它相关的图钉,而不是允许选择更改为此注释。

关于ios - 如何使 MKAnnotationView 触敏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8648263/

相关文章:

iphone - 如何撤消 SVN 上的更新

ios - 通过动态 URL 发现从 NSDictionary 到 NSArray

iphone - 为什么仪器不执行我的 Monotouch 应用程序?

ios - Objective-C:获取不可见的自定义 UITableViewCell 上的属性值

iOS 确定视频中的帧数

ios - 在 Swift 中使用两个 Storyboard

iphone - UIImagePickerController 无法选择图片

iphone - 隐藏 UIButton 标题

ios - 如何在 tableView 之前添加 "Loading" View Controller

ios - 在 UICollectionViewController 中按下 UICollectionViewCell 后无响应