iosswiftmulti-touchuitouch

Getting the identifier of a touch


I am trying to identify a touch throughout touchesBegan, touchesMoved and touchesEnded.

When printing the UITouch (the entire set) to the console I noticed a String at the beginning, that seems to remain constant for each finger on the screen.

[<UITouch: 0x100d362e0> phase: ...

How do I retrieve this property?


Solution

  • I'm not 100% sure what you are asking but think you can use this as a start to tracking unique touch instances, though I'm not sure how reliable it will be given that we don't create the touch event.

    import UIKit
    
    class ViewController: UIViewController {
    
        var touches: [UITouch] = []
    
        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            self.touches.append(contentsOf: touches)
        }
    
        override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
            touches.forEach {
                let index = self.touches.index(of: $0)
                print(String.init(describing: index))
            }
        }
    
        override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
            touches.forEach {
                let index = self.touches.index(of: $0)
                print(String.init(describing: index))
            }
        }
    }