私は iPad 用のグラフ電卓アプリに取り組んでおり、ユーザーがグラフ ビューの領域をタップして、タッチしたポイントの座標を表示するテキスト ボックスをポップアップ表示できる機能を追加したいと考えていました。これからCGPointを取得するにはどうすればよいですか?
6 に答える
あなたは双方向を持っています...
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];
ここで、このコードは、特定のオブジェクトまたはメインビューのサブビューで何かをしたいときに使用します
これを試して
- (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);
}
ユーザーがタッチダウンした場所ではなく、画面から指を離した場所を確認したい場合は、「touchesEnded」を使用できます。
APIの見た目がまったく異なるため、Swift 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
}
}
また
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
、ビューで触れたポイントが含まれます。
UIGestureRecognizer をサブクラス化して手動でタッチをインターセプトするよりも、マップ ビューで 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 : 最後に、ジェスチャー ハンドラーを実装します。
- (void)tapGestureHandler:(UITapGestureRecognizer *)tgr
{
CGPoint touchPoint = [tgr locationInView:mapView];
CLLocationCoordinate2D touchMapCoordinate
= [mapView convertPoint:touchPoint toCoordinateFromView:mapView];
NSLog(@"tapGestureHandler: touchMapCoordinate = %f,%f",
touchMapCoordinate.latitude, touchMapCoordinate.longitude);
}
UIGestureRecognizer
またはUITouch
オブジェクトを使用する場合、 メソッドを使用して、ユーザーがタッチした特定のビュー内でlocationInView:
を取得できます。CGPoint