2012-05-11 7 views
26

私はiPad用のグラフ電卓アプリに取り組んでいます。グラフビューでユーザーが領域をタップして、タッチしたポイントの座標を表示するテキストボックスをポップアップできるようにする機能を追加したかったのです。これからどのようにCGPointを手に入れることができますか?タップされた場所からCGPointを取得するには?

答えて

46

次の2つの方法を持っている...ここ

1.

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touch = [[event allTouches] anyObject]; 
    CGPoint location = [touch locationInView:touch.view]; 
} 

、あなたは...現在のビューからのポイントで場所を得ることができます

2.

UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)]; 
[tapRecognizer setNumberOfTapsRequired:1]; 
[tapRecognizer setDelegate:self]; 
[self.view addGestureRecognizer:tapRecognizer]; 

ここでは、このコードは、perticularオブジェクトやメインビューのサブビューで何かしたいときに使用します

19

は、ユーザーではなく、彼らが着陸場所の画面から指を持ち上げたところあなたはむしろ見たい場合は、「touchesEnded」を使用することができます。この

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touch = [touches anyObject]; 

    // Get the specific point that was touched 
    CGPoint point = [touch locationInView:self.view]; 
    NSLog(@"X location: %f", point.x); 
    NSLog(@"Y Location: %f",point.y); 

} 

を試してみてください。

3

UIGestureRecognizerまたはUITouchオブジェクトを使用する場合は、locationInView:メソッドを使用して、ユーザーがタッチした特定のビュー内のCGPointを取得できます。

6

UIGestureRecognizerをマップビューで使用する方が、サブクラス化して手作業で傍受するのではなく、おそらくもっと簡単で簡単です。

ステップ1:まず、マップビューにジェスチャー認識を追加します。

UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] 
    initWithTarget:self action:@selector(tapGestureHandler:)]; 
tgr.delegate = self; //also add <UIGestureRecognizerDelegate> to @interface 
[mapView addGestureRecognizer:tgr]; 

ステップ2:次に、ので、あなたのタップジェスチャー認識は、マップの(と同時に作業することができますshouldRecognizeSimultaneouslyWithGestureRecognizerを実装し、YESを返しますそうでない場合は)マップが自動的に処理し得ることはありませんピンをタップする:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer 
shouldRecognizeSimultaneouslyWithGestureRecognizer 
    :(UIGestureRecognizer *)otherGestureRecognizer 
{ 
    return YES; 
} 

ステップ3:

:最後に、ジェスチャーハンドラを実装APIが見てかなり異なっているので
+1

これは完璧な回答です –

0
func handleFrontTap(gestureRecognizer: UITapGestureRecognizer) { 
    print("tap working") 
    if gestureRecognizer.state == UIGestureRecognizerState.Recognized { 
     `print(gestureRecognizer.locationInView(gestureRecognizer.view))` 
    } 
} 
3

ちょうどスウィフト4答えにトスしたいです。

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
    if let touch = event?.allTouches?.first { 
     let loc:CGPoint = touch.location(in: touch.view) 
     //insert your touch based code here 
    } 
} 

OR

let tapGR = UITapGestureRecognizer(target: self, action: #selector(tapped)) 
view.addGestureRecognizer(tapGR) 

@objc func tapped(gr:UITapGestureRecognizer) { 
    let loc:CGPoint = gr.location(in: gr.view) 
    //insert your touch based code here 
} 

どちらの場合もlocは、ビューに感動したポイントが含まれています。

関連する問題