59

ユーザーが MKMapView に触れるポイントの座標を取得する必要がありました。Interface Builder を使用していません。一例を挙げていただけますか?

4

2 に答える 2

196

これにはUILongPressGestureRecognizerを使用できます。mapview を作成または初期化する場合は常に、最初に認識エンジンをそれにアタッチします。

UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] 
    initWithTarget:self action:@selector(handleLongPress:)];
lpgr.minimumPressDuration = 2.0; //user needs to press for 2 seconds
[self.mapView addGestureRecognizer:lpgr];
[lpgr release];

次に、ジェスチャ ハンドラーで次のようにします。

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

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

    YourMKAnnotationClass *annot = [[YourMKAnnotationClass alloc] init];
    annot.coordinate = touchMapCoordinate;
    [self.mapView addAnnotation:annot];
    [annot release];
}

YourMKAnnotationClass は、 MKAnnotationプロトコルに準拠する、ユーザーが定義するクラスです。アプリを iOS 4.0 以降でのみ実行する場合は、代わりに定義済みのMKPointAnnotationクラスを使用できます。

独自の MKAnnotation クラスを作成する例については、サンプル アプリMapCalloutsを参照してください。

于 2010-10-18T15:38:47.047 に答える