问题
I have been researching everywhere and can't find if there is a unique identifier for each touch point in ios. I also would like to know how to access that in swift but can't find any documentation on it.
回答1:
Not really for each point, but for each touch. To access them requires your own touch handling, for example in the UIView where the touches occur or its ViewController. This simply requires you to write your own methods for touchesBegan:withEvent:
, touchesMoved:withEvent:
and touchesEnded:withEvent:
.
When touchesBegan:withEvent:
, touchesMoved:withEvent:
and touchesEnded:withEvent:
are called by iOS, they report the touches in an NSSet
. Each member of that set is a unique pointer to the touch data structure, and you should use them as the keys in an NSMutableDictionary
if you want to filter touches over time.
Like that in touchesBegan
, when you encounter a touch for the first time:
var pointDict: [String?: NSObject?] = [:]
...
func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
// Regular multitouch handling.
for touch in touches.allObjects as UITouch {
// Create a new key from the UITouch pointer:
let key = \(touch)
// Put the point into the dictionary as an NSValue
pointDict.setValue(NSValue(CGPoint: touch.locationInView(myView)), forKey:key)
}
}
Now in touchesMoved
you need to check the pointer against the stored keys:
func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
for touch in touches.allObjects as UITouch {
// Create a new key from the UITouch pointer:
let key = \(touch)
// See if the key has been used already:
let oldPoint = pointDict[key]
if oldPoint != nil {
(do whatever is needed to continue the point sequence here)
}
}
}
If there is already an entry which uses the same touchID as its key, you get the stored object for the key back. If no previous touch used that ID, the dictionary will return nil when you ask it for the corresponding object.
Now you can assign your own pointers to those touch points, knowing that they all belong to the same touch event.
来源:https://stackoverflow.com/questions/27746459/is-there-a-pointer-for-each-touch-point-in-ios