获取Swift中多个触摸的坐标 [英] Get coordinates of multiple touches in Swift

查看:374
本文介绍了获取Swift中多个触摸的坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我一直在试图获取屏幕上的触摸坐标。到目前为止,我可以得到一个触摸的坐标:

 覆盖func touchesBegan(触摸:NSSet,withEvent事件:UIEvent) {
让touch = touches.anyObject()!作为UITouch
让location = touch.locationInView(self.view)
println(location)
}

但是当用两根手指触摸时,我只得到第一次触摸的坐标。多点触控工作(我使用这个小教程测试:



否则你总是只需触摸 touchesBegan 请参阅此处的文档)。



然后,在内搜索touchBegan ,迭代一组触摸以获得它们的坐标:

 覆盖func touchesBegan(_ touches:Set< ; UITouch>,有事件:UIEvent?){
触摸触摸{
let location = touch.location(in:self.view)
print(location)
}
}


So I've been messing around trying to get the coordinates of touches on the screen. So far I can get the coordinates of one touch with this:

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

But when touching with two fingers I only get the coordinates of the first touch. Multi-touch works (I tested with this little tutorial: http://www.techotopia.com/index.php/An_Example_Swift_iOS_8_Touch,_Multitouch_and_Tap_Application). So my question is, how do I get the coordinates of the second (and third, fourth...) touch?

解决方案

** Updated to Swift 4 and Xcode 9 (8 Oct 2017) **

First of all, remember to enable multi-touch events by setting

self.view.isMultipleTouchEnabled = true

in your UIViewController's code, or using the appropriate storyboard option in Xcode:

Otherwise you'll always get a single touch in touchesBegan (see documentation here).

Then, inside touchesBegan, iterate over the set of touches to get their coordinates:

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

这篇关于获取Swift中多个触摸的坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆