Search code examples
iosswiftxcodeuitouch

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


Hey in trying to track multiple touches and i get this error. And I know why i get the error its because of the Set at the top of the touchesbegin function. but i have to keep my Set in the overrideBegin. so how would i solve this error and make this code error free with out changing the Orignal override values.

enter image description here

Code:

  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
    }

  }

Solution

  • You can use .count on touches without converting it to an array. but there's no need as you can iterate over the touches set.

    To be able to register multiple touches you need to add this line to your viewDidLoad() method: view.multipleTouchEnabled = true

    And modify touchesBegan like this:

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