iPhone:MKMapViewにタップを検出
-
16-09-2019 - |
質問
どのように私はMKMapView
のインスタンスでシングルタップを検出していますか?私はMKMapView
をサブクラス化し、その後touchesEnded
メソッドをオーバーライドする必要がありますか?
おかげで、
-Chris
解決
は、これが役立つことを願っています:どのように切片はMKMapViewかのUIWebViewオブジェクトのイベントに触れるですか
他のヒント
、あなたはUITapGestureRecognizer
を使用したいと思います。それはちょうどこのようないくつかのコードを入れ、超簡単です。
UITapGestureRecognizer* tapRec = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(didTapMap:)];
[theMKMapView addGestureRecognizer:tapRec];
[tapRec release];
これはdidTapMap
は、タップジェスチャーとを受信するたびにtheMKMapView
を呼び出しますすべてのピンチ、そして、彼らは以前と同様にドラッグジェスチャーがまだ動作します。
の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 ...
}
それともあなたがしようとしているものに応じて、(コールアウトで、プッシュピン)MKAnnotation
を追加し、あなたが上をタップする何かを持っているので - 。その後、あなたのマップデリゲートがイベントなどを受け取ることになります。
mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
あなたは、マップビュー上のこの時間インターセプトタッチでカント、あなたはそこに不透明なビューを積層してみてください、それはタッチを拾うかどうかを確認することができます...
だけの@ TT-kilew答えの例として、いくつかのコードスニペットを追加します。私の場合、地図上の自身にユーザーを指すようにしたいが、彼のドラッグtouchを中断する必要はありません。
@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
何も私が今までに加工さ見つからなかったが、私はこのunperfect解決策を思い付きました: 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)
}