从我接触触摸屏的位置获取坐标

Luk*_*öhl 25 touchscreen coordinates swift

我尝试从触摸屏触摸位置获取坐标,然后在此处放置特定的UIImage.

我怎样才能做到这一点?

Mun*_*ndi 39

UIResponder子类中,例如UIView:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    let touch = touches.anyObject()! as UITouch
    let location = touch.locationInView(self)
}
Run Code Online (Sandbox Code Playgroud)

这将返回CGPoint视图坐标.

更新了Swift 3语法

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    let touch = touches.first!
    let location = touch.location(in: self)
}
Run Code Online (Sandbox Code Playgroud)

使用Swift 4语法更新

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first!
    let location = touch.location(in: self.view)
}
Run Code Online (Sandbox Code Playgroud)

  • 使用`self.view`. (4认同)
  • @Mundi是对的,只是为了澄清一下,如果你从视图控制器获取触摸位置而不是UIView子类,你的位置线将如下所示:`let location = touch.locationInView(self.view)` (2认同)

小智 19

将此作为Swift 3 - 我正在使用:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let position = touch.location(in: self)
        print(position.x)
        print(position.y)
    }
}
Run Code Online (Sandbox Code Playgroud)

很高兴听到更清晰或更优雅的方式来产生相同的结果


kb9*_*920 15

这是在Swift 2.0中的工作

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {
        let position :CGPoint = touch.locationInView(view)
        print(position.x)
        print(position.y)

    }
}
Run Code Online (Sandbox Code Playgroud)