如何检测对 的实例的单击MKMapView
?我必须子类MKMapView
化然后重写该touchesEnded
方法吗?
谢谢,
-克里斯
如何检测对 的实例的单击MKMapView
?我必须子类MKMapView
化然后重写该touchesEnded
方法吗?
谢谢,
-克里斯
如果您只是希望在不影响地图的任何其他触摸行为的情况下获得点击手势的通知,您将需要使用UITapGestureRecognizer
. 超级简单,只要输入一些这样的代码。
UITapGestureRecognizer* tapRec = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(didTapMap:)];
[theMKMapView addGestureRecognizer:tapRec];
[tapRec release];
这将调用didTapMap
每当theMKMapView
接收到点击手势和所有捏合和拖动手势仍将像以前一样工作。
或者根据您要执行的操作,添加一个MKAnnotation
(图钉,带有标注),以便您可以点击某些内容 - 然后您的地图代表将收到一个事件,例如。
mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
希望这会有所帮助:如何拦截 MKMapView 或 UIWebView 对象上的触摸事件?
在 iOS 8 上完美运行
- (void)viewDidLoad
{
[super viewDidLoad];
UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:nil];
doubleTap.numberOfTapsRequired = 2;
doubleTap.numberOfTouchesRequired = 1;
[self.mapView addGestureRecognizer:doubleTap];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
singleTap.numberOfTapsRequired = 1;
singleTap.numberOfTouchesRequired = 1;
[singleTap requireGestureRecognizerToFail: doubleTap];
[self.mapView addGestureRecognizer:singleTap];
}
- (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer
{
if (gestureRecognizer.state != UIGestureRecognizerStateEnded)
return;
//Do your work ...
}
你现在不能拦截地图视图上的触摸,你可以尝试在那里分层一个不透明的视图,看看它是否能接收到触摸......
只需添加一些代码片段作为@tt-kilew 答案的说明。就我而言,我想将用户指向地图上的自己,但不想打断他的拖动触摸。
@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
我没有发现任何工作,但我想出了这个不完美的解决方案:在 viewDidLoad
let singleTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(onMapClicked))
singleTapRecognizer.delegate = self
mapView.addGestureRecognizer(singleTapRecognizer)
在委托中:
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
return touch.view!.frame.equalTo(mapView.frame)
}
swit 5.x 我的 2 美分:
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()
}
}
}
有用。但如果苹果改变视图层,老实说可能会崩溃。更好的识别器。