identifying touches in Swift

742 views Asked by At

Good day,

I'm new to Swift (and object-oriented languages altogether) and I'm creating an iPad app that lets you draw using your finger. I'm currently trying to manage multitouch events correctly, and I'd like to keep track of the touches. The idea is to draw only following one touch, and discard the others, ignoring them even after the initial touch has ended.

For that, I need to identify each touch, but the UITouch object doesn't contain an ID. Actually, since touches are stored in an NSSet, they aren't ordered.

Erring on the internet, I found a possible solution storing the adresses of the touches in a CFDictionary. This seems reasonable in Objective-C, but Swift isn't very pointer-friendly and I haven't managed to create a CFDictionary taking pointers on UITouch as value.

Does anyone know how to handle this ? Am I using CFDictionaries wrong (I tried having UnsafePointer<UITouch> as value) ? Is there another solution that I overlooked ?

Thanks for your help.

1

There are 1 answers

0
mike663 On

I only wanted a simple key for the touch and used string interpolation of the UITouch to get one. The string interpolation of my touch looked like this:

<UITouch: 0x1046355b0> phase: Began tap count: 1 force: 0.000 window: <UIWindow: 0x10462beb0; frame = (0 0; 414 736); gestureRecognizers = <NSArray: 0x1c0247fe0>; layer = <UIWindowLayer: 0x1c02325a0>> view: <SCNView: 0x104624be0 | scene=<SCNScene: 0x1c4129ec0> sceneTime=0.000000 frame={{0, 0}, {414, 736}} pointOfView=<SCNNode: 0x1c43f9400 rot(0.000000 1.000000 0.000000 3.141593) | camera=<SCNCamera: 0x10475af60> | no child>> location in window: {220, 344} previous location in window: {220, 344} location in view: {220, 344} previous location in view: {220, 344}

All I needed was that second part, so I wrote the following method to extract it.

func getTouchKey(touch:UITouch) -> String {
    let interpolation = "\(touch)"
    let parts = interpolation.split(separator: " ", maxSplits: 3, omittingEmptySubsequences: true)
    let touchKey = String(parts[1])
    return touchKey
}

In this case, it returns:

0x1046355b0>

I could clean it up if necessary, but as it's already repeatable over the lifetime of the touch, I didn't add anything else.