类型的值&#39;设置<uitouch>&#39;没有会员&#39; allObjects&#39;

时间:2016-10-02 20:27:41

标签: ios swift xcode uitouch

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

enter image description here

代码:

  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
    }

  }

3 个答案:

答案 0 :(得分:0)

它是斯威夫特的Set,而不是NSSet。尝试:

let touchesArray = Array(touches)

但我发现这里不需要进行此类转换,因为您可以迭代set。试试这个:

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

答案 1 :(得分:0)

为什么不做这样的事情?循环中你的东西需要反击吗?

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

    print(ptTouch)
}

答案 2 :(得分:0)

您可以在.count上使用touches,而无需将其转换为数组。但是没有必要,因为你可以迭代设置的触摸。

为了能够注册多个触摸,您需要将此行添加到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)")
    }

}