2012-05-11 33 views
26

我正在研究iPad的圖形計算器應用程序,我想添加一個功能,用戶可以在圖形視圖中點擊一個區域,使文本框彈出並顯示它們所觸摸的點的座標。我怎樣才能從這個CGPoint?如何從抽頭位置獲取CGPoint?

回答

46

你有兩種方式...

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]; 

這裏,這個代碼使用時,你想與你的主視圖或你的主視圖的子視圖做什麼

19

嘗試這個

- (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」如果你寧願看到用戶解除他們的手指離開屏幕,而不是在那裏降落。

3

如果您使用的是UIGestureRecognizerUITouch對象,則可以使用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:最後,實現手勢處理機:

- (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); 
} 
+1

這是一個很好的完整答案 –

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

只想在斯威夫特4答案折騰,因爲API是完全不同的期待。

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將包含在視圖觸摸的點。