'Set<UITouch>' 类型的值没有成员 'allObjects'

Value of type 'Set<UITouch>' has no member 'allObjects'

嘿,在尝试跟踪多次触摸时我收到了这个错误。而且我知道为什么我会因为 touchesbegin 函数顶部的 Set 而得到错误。但我必须将我的 Set 保留在 overrideBegin 中。那么我将如何解决此错误并在不更改原始覆盖值的情况下使此代码无错误。

代码:

  override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {


    var touchesArray = touches.allObjects()
    var nNumTouches = touchesArray.count
    var touch: UITouch!
    var ptTouch = CGPoint.zero
    for nTouch in 0..<nNumTouches {
        touch = touchesArray[nTouch]
        ptTouch = touch.locationInView(self.view)
        //I need it to print the location of each individual touch like finger 1 or finger 2 is in this location
    }

  }

是Swift的Set,不是NSSet。尝试:

let touchesArray = Array(touches)

但我发现这里不需要这样的转换,因为你可以迭代集合。只试试这个:

for touch in touches {
    let point = touch.location(in: self.view)
    print("x: \(point.x), y: \(point.y)")
}

为什么不做这样的东西呢?你的循环中的东西需要计数器吗?

let touchesArray = touches
var ptTouch: CGPoint?
for touch in touchesArray {
    ptTouch = touch.locationInView(self.view)

    print(ptTouch)
}

您可以在 touches 上使用 .count 而无需将其转换为数组。但没有必要,因为您可以遍历触摸集。

为了能够注册多个触摸,您需要将此行添加到您的 viewDidLoad() 方法中:view.multipleTouchEnabled = true

并像这样修改touchesBegan

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    for (index,touch) in touches.enumerate() {
        let ptTouch = touch.locationInView(self.view)
        print("Finger \(index+1): x=\(pTouch.x) , y=\(pTouch.y)")
    }

}