O'Reilly logo

Cocoa Programming for OS X: The Big Nerd Ranch Guide by Aaron Hillegass, Adam Preble, Nate Chandler

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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​:​ ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required