96

我不确定我做错了什么,但我试图抓住一个MKMapView物体。我通过创建以下类对其进行了子类化:

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>

@interface MapViewWithTouches : MKMapView {

}

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *) event;   

@end

和实施:

#import "MapViewWithTouches.h"
@implementation MapViewWithTouches

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *) event {

    NSLog(@"hello");
    //[super touchesBegan:touches   withEvent:event];

}
@end

但看起来当我使用这个类时,我在控制台上什么也看不到:

MapViewWithTouches *mapView = [[MapViewWithTouches alloc] initWithFrame:self.view.frame];
[self.view insertSubview:mapView atIndex:0];

知道我做错了什么吗?

4

15 回答 15

149

我发现实现这一目标的最佳方法是使用手势识别器。其他方式最终涉及大量不完美地复制 Apple 代码的骇人听闻的编程,尤其是在多点触控的情况下。

这就是我所做的:实现一个无法阻止且无法阻止其他手势识别器的手势识别器。将其添加到地图视图中,然后根据您的喜好使用gestureRecognizer 的touchesBegan、touchesMoved 等。

如何检测 MKMapView 内的任何点击(无技巧)

WildcardGestureRecognizer * tapInterceptor = [[WildcardGestureRecognizer alloc] init];
tapInterceptor.touchesBeganCallback = ^(NSSet * touches, UIEvent * event) {
        self.lockedOnUserLocation = NO;
};
[mapView addGestureRecognizer:tapInterceptor];

通配符手势识别器.h

//
//  WildcardGestureRecognizer.h
//  Copyright 2010 Floatopian LLC. All rights reserved.
//

#import <Foundation/Foundation.h>

typedef void (^TouchesEventBlock)(NSSet * touches, UIEvent * event);

@interface WildcardGestureRecognizer : UIGestureRecognizer {
    TouchesEventBlock touchesBeganCallback;
}
@property(copy) TouchesEventBlock touchesBeganCallback;


@end

通配符手势识别器.m

//
//  WildcardGestureRecognizer.m
//  Created by Raymond Daly on 10/31/10.
//  Copyright 2010 Floatopian LLC. All rights reserved.
//

#import "WildcardGestureRecognizer.h"


@implementation WildcardGestureRecognizer
@synthesize touchesBeganCallback;

-(id) init{
    if (self = [super init])
    {
        self.cancelsTouchesInView = NO;
    }
    return self;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (touchesBeganCallback)
        touchesBeganCallback(touches, event);
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
}

- (void)reset
{
}

- (void)ignoreTouch:(UITouch *)touch forEvent:(UIEvent *)event
{
}

- (BOOL)canBePreventedByGestureRecognizer:(UIGestureRecognizer *)preventingGestureRecognizer
{
    return NO;
}

- (BOOL)canPreventGestureRecognizer:(UIGestureRecognizer *)preventedGestureRecognizer
{
    return NO;
}

@end

斯威夫特 3

let tapInterceptor = WildCardGestureRecognizer(target: nil, action: nil)
tapInterceptor.touchesBeganCallback = {
    _, _ in
    self.lockedOnUserLocation = false
}
mapView.addGestureRecognizer(tapInterceptor)

WildCardGestureRecognizer.swift

import UIKit.UIGestureRecognizerSubclass

class WildCardGestureRecognizer: UIGestureRecognizer {

    var touchesBeganCallback: ((Set<UITouch>, UIEvent) -> Void)?

    override init(target: Any?, action: Selector?) {
        super.init(target: target, action: action)
        self.cancelsTouchesInView = false
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
        super.touchesBegan(touches, with: event)
        touchesBeganCallback?(touches, event)
    }

    override func canPrevent(_ preventedGestureRecognizer: UIGestureRecognizer) -> Bool {
        return false
    }

    override func canBePrevented(by preventingGestureRecognizer: UIGestureRecognizer) -> Bool {
        return false
    }
}
于 2010-10-31T18:44:12.337 回答
29

经过一天的比萨饼,尖叫声,我终于找到了解决方案!很整齐!

彼得,我在上面使用了你的技巧并对其进行了一些调整,最终得到了一个与 MKMapView 完美配合的解决方案,并且也应该与 UIWebView 配合使用

MKTouchAppDelegate.h

#import <UIKit/UIKit.h>
@class UIViewTouch;
@class MKMapView;

@interface MKTouchAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    UIViewTouch *viewTouch;
    MKMapView *mapView;
}
@property (nonatomic, retain) UIViewTouch *viewTouch;
@property (nonatomic, retain) MKMapView *mapView;
@property (nonatomic, retain) IBOutlet UIWindow *window;

@end

MKTouchAppDelegate.m

#import "MKTouchAppDelegate.h"
#import "UIViewTouch.h"
#import <MapKit/MapKit.h>

@implementation MKTouchAppDelegate

@synthesize window;
@synthesize viewTouch;
@synthesize mapView;


- (void)applicationDidFinishLaunching:(UIApplication *)application {

    //We create a view wich will catch Events as they occured and Log them in the Console
    viewTouch = [[UIViewTouch alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];

    //Next we create the MKMapView object, which will be added as a subview of viewTouch
    mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
    [viewTouch addSubview:mapView];

    //And we display everything!
    [window addSubview:viewTouch];
    [window makeKeyAndVisible];


}


- (void)dealloc {
    [window release];
    [super dealloc];
}


@end

UIViewTouch.h

#import <UIKit/UIKit.h>
@class UIView;

@interface UIViewTouch : UIView {
    UIView *viewTouched;
}
@property (nonatomic, retain) UIView * viewTouched;

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event;

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;

@end

UIViewTouch.m

#import "UIViewTouch.h"
#import <MapKit/MapKit.h>

@implementation UIViewTouch
@synthesize viewTouched;

//The basic idea here is to intercept the view which is sent back as the firstresponder in hitTest.
//We keep it preciously in the property viewTouched and we return our view as the firstresponder.
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    NSLog(@"Hit Test");
    viewTouched = [super hitTest:point withEvent:event];
    return self;
}

//Then, when an event is fired, we log this one and then send it back to the viewTouched we kept, and voilà!!! :)
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"Touch Began");
    [viewTouched touchesBegan:touches withEvent:event];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"Touch Moved");
    [viewTouched touchesMoved:touches withEvent:event];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"Touch Ended");
    [viewTouched touchesEnded:touches withEvent:event];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"Touch Cancelled");
}

@end

我希望这会帮助你们中的一些人!

干杯

于 2009-06-27T15:30:05.757 回答
24
UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleGesture:)];   
tgr.numberOfTapsRequired = 2;
tgr.numberOfTouchesRequired = 1;
[mapView addGestureRecognizer:tgr];
[tgr release];


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

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

    //.............
}
于 2011-06-24T10:20:49.547 回答
12

对于 MKMapView 来说,真正可行的解决方案是手势识别!

我想在拖动地图或捏缩放时停止更新我所在位置的地图中心。

因此,创建手势识别器并将其添加到 mapView :

- (void)viewDidLoad {

    ...

    // Add gesture recognizer for map hoding
    UILongPressGestureRecognizer *longPressGesture = [[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressAndPinchGesture:)] autorelease];
    longPressGesture.delegate = self;
    longPressGesture.minimumPressDuration = 0;  // In order to detect the map touching directly (Default was 0.5)
    [self.mapView addGestureRecognizer:longPressGesture];

    // Add gesture recognizer for map pinching
    UIPinchGestureRecognizer *pinchGesture = [[[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressAndPinchGesture:)] autorelease];
    pinchGesture.delegate = self;
    [self.mapView addGestureRecognizer:pinchGesture];

    // Add gesture recognizer for map dragging
    UIPanGestureRecognizer *panGesture = [[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)] autorelease];
    panGesture.delegate = self;
    panGesture.maximumNumberOfTouches = 1;  // In order to discard dragging when pinching
    [self.mapView addGestureRecognizer:panGesture];
}

查看UIGestureRecognizer 类参考以查看所有可用的手势识别器。

因为我们已经将委托定义为 self,所以我们必须实现协议 UIGestureRecognizerDelegate :

typedef enum {
    MapModeStateFree,                    // Map is free
    MapModeStateGeolocalised,            // Map centred on our location
    MapModeStateGeolocalisedWithHeading  // Map centred on our location and oriented with the compass
} MapModeState;

@interface MapViewController : UIViewController <CLLocationManagerDelegate, UIGestureRecognizerDelegate> {
    MapModeState mapMode;
}

@property (nonatomic, retain) IBOutlet MKMapView *mapView;
...

并覆盖方法 gestureRecognizer:gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer: 为了允许同时识别多个手势,如果我理解正确的话:

// Allow to recognize multiple gestures simultaneously (Implementation of the protocole UIGestureRecognizerDelegate)
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

现在编写我们的手势识别器将调用的方法:

// On map holding or pinching pause localise and heading
- (void)handleLongPressAndPinchGesture:(UIGestureRecognizer *)sender {
    // Stop to localise and/or heading
    if (sender.state == UIGestureRecognizerStateBegan && mapMode != MapModeStateFree) {
        [locationManager stopUpdatingLocation];
        if (mapMode == MapModeStateGeolocalisedWithHeading) [locationManager stopUpdatingHeading];
    }
    // Restart to localise and/or heading
    if (sender.state == UIGestureRecognizerStateEnded && mapMode != MapModeStateFree) {
        [locationManager startUpdatingLocation];
        if (mapMode == MapModeStateGeolocalisedWithHeading) [locationManager startUpdatingHeading];
    }
}

// On dragging gesture put map in free mode
- (void)handlePanGesture:(UIGestureRecognizer *)sender {
    if (sender.state == UIGestureRecognizerStateBegan && mapMode != MapModeStateFree) [self setMapInFreeModePushedBy:sender];
}
于 2011-04-20T00:55:34.217 回答
7

以防万一有人像我一样尝试做同样的事情:我想在用户点击的地方创建一个注释。为此,我使用了UITapGestureRecognizer解决方案:

UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapOnMap:)];
[self.mapView addGestureRecognizer:tapGestureRecognizer];
[tapGestureRecognizer setDelegate:self];

- (void)didTapOnMap:(UITapGestureRecognizer *)gestureRecognizer
{
    CGPoint point = [gestureRecognizer locationInView:self.mapView];
    CLLocationCoordinate2D coordinate = [self.mapView convertPoint:point toCoordinateFromView:self.mapView];
    .......
}

但是,didTapOnMap:当我点击注释时也会调用它,并且会创建一个新注释。解决方案是实施UIGestureRecognizerDelegate

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([touch.view isKindOfClass:[MKAnnotationView class]])
    {
        return NO;
    }
    return YES;
}
于 2015-03-29T15:20:17.513 回答
3

您可能需要覆盖一个透明视图来捕捉触摸,就像经常使用基于 UIWebView 的控件一样。地图视图已经通过触摸做了很多特殊的事情,以允许地图被移动、居中、缩放等......消息不会冒泡到您的应用程序中。

我能想到的另外两个(未测试)选项:

1) 通过 IB 退出第一响应者并将其设置为“文件的所有者”以允许文件的所有者响应触摸。我怀疑这会起作用,因为 MKMapView 扩展了 NSObject,而不是 UIView,因此触摸事件可能仍然不会传播给你。

2)如果你想在地图状态改变(比如缩放)时捕获,只需实现 MKMapViewDelegate 协议来监听特定事件。我的预感是,这是您轻松捕获一些交互的最佳方法(没有在地图上实现透明视图)。不要忘记将包含 MKMapView 的 View Controller 设置为地图的委托 ( map.delegate = self)。

祝你好运。

于 2009-06-26T16:21:57.013 回答
2

我还没有尝试过,但是 MapKit 很有可能是基于类集群的,因此对其进行子类化是困难且无效的。

我建议将 MapKit 视图设为自定义视图的子视图,这样您就可以在触摸事件到达之前拦截它们。

于 2009-06-26T16:01:56.650 回答
2

所以在搞砸了半天之后,我发现了以下内容:

  1. 正如其他人发现的那样,捏是行不通的。我尝试了子类化 MKMapView 和上述方法(拦截它)。结果是一样的。
  2. 在斯坦福的 iPhone 视频中,一位来自 Apple 的人说如果你“转移”触摸请求(也就是上面描述的两种方法),许多 UIKit 的东西会导致很多错误,而且你可能无法让它工作。

  3. 解决方案:在这里描述:拦截/劫持 MKMapView 的 iPhone 触摸事件。基本上,您在任何响应者得到它之前“捕获”事件,并在那里解释它。

于 2010-03-08T08:30:17.380 回答
2

在 Swift 3.0 中

import UIKit
import MapKit

class CoordinatesPickerViewController: UIViewController {

    @IBOutlet var mapView: MKMapView!
    override func viewDidLoad() {
        super.viewDidLoad()

        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(clickOnMap))
        mapView.addGestureRecognizer(tapGestureRecognizer)
    }

    @objc func clickOnMap(_ sender: UITapGestureRecognizer) {

        if sender.state != UIGestureRecognizerState.ended { return }
        let touchLocation = sender.location(in: mapView)
        let locationCoordinate = mapView.convert(touchLocation, toCoordinateFrom: mapView)
        print("Tapped at lat: \(locationCoordinate.latitude) long: \(locationCoordinate.longitude)")

    }

}
于 2017-07-03T09:11:47.193 回答
0

使 MKMapView 成为自定义视图的子视图并实现

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event

在自定义视图中返回 self 而不是子视图。

于 2009-06-27T03:08:25.653 回答
0

谢谢你的披萨和尖叫——你为我节省了很多时间。

multipletouchenabled 将偶尔工作。

viewTouch.multipleTouchEnabled = TRUE;

最后,当我需要捕捉触摸时,我切换了视图(与需要捏缩放不同的时间点):

    [mapView removeFromSuperview];
    [viewTouch addSubview:mapView];
    [self.view insertSubview:viewTouch atIndex:0];
于 2009-07-22T12:14:10.157 回答
0

我注意到您可以跟踪触摸的数量和位置,并在视图中获取每个触摸的位置:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"Touch Moved %d", [[event allTouches] count]);

 NSEnumerator *enumerator = [touches objectEnumerator];
 id value;

 while ((value = [enumerator nextObject])) {
  NSLog(@"touch description %f", [value locationInView:mapView].x);
 }
    [viewTouched touchesMoved:touches withEvent:event];
}

有没有其他人尝试使用这些值来更新地图的缩放级别?这将是记录开始位置,然后是结束位置,计算相对差异并更新地图的问题。

我正在使用 Martin 提供的基本代码,这看起来可以工作......

于 2009-12-14T23:43:11.460 回答
0

这是我放在一起的内容,它确实允许在模拟器中进行捏缩放(尚未在真正的 iPhone 上尝试过),但我认为会很好:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"Touch Began %d", [touches count]);
 reportTrackingPoints = NO;
 startTrackingPoints = YES;
    [viewTouched touchesBegan:touches withEvent:event];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
 if ([[event allTouches] count] == 2) {
  reportTrackingPoints = YES;
  if (startTrackingPoints == YES) {
   BOOL setA = NO;
   NSEnumerator *enumerator = [[event allTouches] objectEnumerator];
   id value;
   while ((value = [enumerator nextObject])) {
    if (! setA) {
     startPointA = [value locationInView:mapView];
     setA = YES;
    } else {
     startPointB = [value locationInView:mapView];
    }
   }
   startTrackingPoints = NO;
  } else {
   BOOL setA = NO;
   NSEnumerator *enumerator = [[event allTouches] objectEnumerator];
   id value;
   while ((value = [enumerator nextObject])) {
    if (! setA) {
     endPointA = [value locationInView:mapView];
     setA = YES;
    } else {
     endPointB = [value locationInView:mapView];
    }
   }
  }
 }
 //NSLog(@"Touch Moved %d", [[event allTouches] count]);
    [viewTouched touchesMoved:touches withEvent:event];
}

- (void) updateMapFromTrackingPoints {
 float startLenA = (startPointA.x - startPointB.x);
 float startLenB = (startPointA.y - startPointB.y);
 float len1 = sqrt((startLenA * startLenA) + (startLenB * startLenB));
 float endLenA = (endPointA.x - endPointB.x);
 float endLenB = (endPointA.y - endPointB.y);
 float len2 = sqrt((endLenA * endLenA) + (endLenB * endLenB));
 MKCoordinateRegion region = mapView.region;
 region.span.latitudeDelta = region.span.latitudeDelta * len1/len2;
 region.span.longitudeDelta = region.span.longitudeDelta * len1/len2;
 [mapView setRegion:region animated:YES];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
 if (reportTrackingPoints) {
  [self updateMapFromTrackingPoints];
  reportTrackingPoints = NO;
 }


    [viewTouched touchesEnded:touches withEvent:event];
}

主要思想是,如果用户使用两根手指,您可以跟踪这些值。我在 startPoints A 和 B 中记录了起点和终点。然后我记录了当前的跟踪点,当我完成后,在 touchesEnded 上,我可以调用一个例程来计算我开始的点之间的线的相对长度,以及我使用简单斜边计算结束的点之间的线。它们之间的比率是缩放量:我将区域跨度乘以该量。

希望它对某人有用。

于 2009-12-15T01:39:03.683 回答
0

我从 MystikSpiral 的回答中采用了“覆盖”透明视图的想法,它非常适合我想要实现的目标;快速、清洁的解决方案。

简而言之,我有一个自定义 UITableViewCell(在 IB 中设计),左侧有 MKMapView,右侧有一些 UILabel。我想制作自定义单元格,以便您可以在任何地方触摸它,这将推动一个新的视图控制器。然而,触摸地图并没有将触摸“向上”传递给 UITableViewCell,直到我简单地在其顶部(在 IB 中)添加了一个与地图视图相同大小的 UIView,并使其成为代码中的“清晰颜色”的背景(不认为你可以在 IB 中设置 clearColor 吗??):

dummyView.backgroundColor = [UIColor clearColor];

认为它可能会帮助别人;当然,如果您想为表格视图单元格实现相同的行为。

于 2010-04-06T14:03:23.130 回答
0

我不明白为什么其他答案如此复杂。解决方案实际上只有一行:

mapView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(mapTapped)))

@objc func mapTapped() {}
于 2020-12-30T00:19:08.383 回答