[英]How do I get the coordinates for finger tapping in UIView?
如何獲取 UIView 中手指敲擊的坐標? (我寧願不使用一大堆按鈕)
謝謝
有兩種方法可以做到這一點。 如果您已經擁有正在使用的 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,並且視圖由視圖 controller 或其他任何東西擁有,那么您可以使用 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
}
}
Swift 3 個回答
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapAction(_:)))
yourView.addGestureRecognizer(tapGesture)
func tapAction(_ sender: UITapGestureRecognizer) {
let point = sender.location(in: yourView)
}
func handleFrontTap(gestureRecognizer: UITapGestureRecognizer) {
print("tap working")
if gestureRecognizer.state == UIGestureRecognizerState.Recognized
{
`print(gestureRecognizer.locationInView(gestureRecognizer.view))`
}
}
我假設您的意思是識別手勢(和觸摸)。 開始尋找如此廣泛的問題的最佳起點是 Apple 的示例代碼Touches 。 它遍歷了大量的信息。
- (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
的一個方法, UIView
和UIViewController
都派生自該方法。 如果你用谷歌搜索這個方法,那么你會發現幾個教程。 Apple 提供的MoveMe示例是一個不錯的示例。
Swift 5.6:
您可以在 UIResponder 中覆蓋以下內容(UIView 和 UIViewController 都繼承自):
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let point = touch.location(in: someView)
print("x = \(point.x), y = \(point.y)")
}
}
或者在您的手勢識別器處理程序中:
@objc func handleLongPress(gestureRecognizer: UILongPressGestureRecognizer) {
let point = gestureRecognizer.location(in: someView)
print("x = \(point.x), y = \(point.y)")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.