小编典典

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

swift

我尝试从点击触摸屏的位置获取坐标,以在此时放置特定的UIImage。

我怎样才能做到这一点?


阅读 535

收藏
2020-07-07

共1个答案

小编典典

UIResponder子类中,例如UIView

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

这将返回一个CGPoint视图坐标。

使用Swift 3语法更新

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

使用Swift 4语法更新

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first!
    let location = touch.location(in: self.view)
}
2020-07-07