Getting the coordinates from the location I touch

2019-01-11 13:17发布

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?

4条回答
姐就是有狂的资本
2楼-- · 2019-01-11 13:54

Swift 4.0

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let position = touch.location(in: view)
        print(position)
    }
}

source

查看更多
forever°为你锁心
3楼-- · 2019-01-11 14:06

This is work in 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)

    }
}
查看更多
该账号已被封号
4楼-- · 2019-01-11 14:08

Taking this forward for Swift 3 - I'm using:

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)
    }
}

Happy to hear any clearer or more elegant ways to produce the same result

查看更多
Rolldiameter
5楼-- · 2019-01-11 14:18

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<UITouch>, with event: UIEvent?) {
    let touch = touches.first!
    let location = touch.location(in: self)
}
查看更多
登录 后发表回答