Improving Hit Detection

The hit testing in DieView is pretty lazy. If the user clicks anywhere in the view, the die reacts. It would be better if the die only depressed when the user clicked in the die’s rectangle.

CGRect’s contains(_:) function can check whether a rectangle contains a point, and you can get the die’s rectangle from metricsForSize(_:).

There is a hurdle, however: NSEvent provides locationInWindow, but what you need is the point in the view’s coordinate system, which dieFrame is in. How can you convert locationInWindow to the correct coordinate system?

NSView provides a few methods for this very purpose:

 ​ ​ ​ ​f​u​n​c​ ​c​o​n​v​e​r​t​P​o​i​n​t​(​a​P​o​i​n​t​:​ ​N​S​P​o​i​n​t​,​ ​f​r​o​m​V​i​e​w​ ​a​V​i​e​w​:​ ...

Get Cocoa Programming for OS X: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.