Getting the coordinates from the location I touch the touchscreen

后端 未结 6 1278
温柔的废话
温柔的废话 2020-12-03 05:15

I try to get the coordinates from the location where I hit the touchscreen to do put a specific UIImage at this point.

How can I do this?

6条回答
  •  攒了一身酷
    2020-12-03 05:26

    In a UIResponder subclass, such as UIView:

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

    This will return a CGPoint in view coordinates.

    Updated with Swift 3 syntax

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

    Updated with Swift 4 syntax

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

提交回复
热议问题