2011-05-24 27 views

回答

30

有兩種方法可以完成此操作。如果你已經得到了你使用的UIView的子類,你可以重寫-touchesEnded:withEvent:方法上的子類,像這樣:

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *aTouch = [touches anyObject]; 
    CGPoint point = [aTouch locationInView:self]; 
    // point.x and point.y have the coordinates of the touch 
} 

如果你還沒有子類的UIView,雖然和視圖是由視圖控制器擁有或什麼的,那麼你可以使用一個UITapGestureRecognizer,像這樣:

// when the view's initially set up (in viewDidLoad, for example) 
UITapGestureRecognizer *rec = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRecognized:)]; 
[someView addGestureRecognizer:rec]; 
[rec release]; 

// elsewhere 
- (void)tapRecognized:(UITapGestureRecognizer *)recognizer 
{ 
    if(recognizer.state == UIGestureRecognizerStateRecognized) 
    { 
     CGPoint point = [recognizer locationInView:recognizer.view]; 
     // again, point.x and point.y have the coordinates 
    } 
} 
+1

touchesEnded:withEvent:也可以在UIViewController中使用,因爲這也是從UIResponder派生的。 – taskinoor 2011-05-24 16:54:35

+0

謝謝你們......這給了一個好的開始! – jdl 2011-05-24 20:36:13

2

我假設你的意思的手勢識別(和觸摸)。開始尋找這樣一個廣泛問題的最佳地點是Apple的示例代碼Touches。它遍歷了大量的信息。

+0

謝謝你的幫助。 – jdl 2011-05-24 20:39:45

2
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { 
    UITouch *touch = [touches anyObject]; 
    CGPoint touchPoint = [touch locationInView:myView]; 
    NSLog("%lf %lf", touchPoint.x, touchPoint.y); 
} 

你需要做這樣的事情。 touchesBegan:withEvent:UIResponder的一種方法,其中UIViewUIViewController都是從中導出的。如果你谷歌這種方法,那麼你會發現幾個教程。 MoveMe來自蘋果的樣品是一個很好的例子。

+0

謝謝你的幫助。 – jdl 2011-05-24 20:38:35

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

斯威夫特3回答

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapAction(_:))) 
yourView.addGestureRecognizer(tapGesture) 


func tapAction(_ sender: UITapGestureRecognizer) { 

     let point = sender.location(in: yourView) 


}