CGRect and CGGeometry: So much more than just a pretty frame

The objects and classes of iOS make it a powerful platform for programming apps. They also mean that there is an endless amount of documentation. This makes it easy to miss certain elements, especially best practice.

To fill this gap comes the NYTimes Objective-C style guide on GitHub.

I've already been inspired to write one blogpost by this guide and this is a second.

Glancing through the style guide, I happened upon the instructions for CGRect and measuring frame sizes. Now this is eye-opening stuff, because Apple's own documentation and code accesses frame sizes and positions using code like:

- (void) viewDidLayoutSubviews {
CGRect viewBounds = self.view.bounds;
CGFloat bottomBarOffset = self.bottomLayoutGuide.length;
}

And yet, as the NYT guide tells us, Apple's CGGeometry reference warns:

All functions described in this reference that take CGRect data structures as inputs implicitly standardize those rectangles before calculating their results. For this reason, your applications should avoid directly reading and writing the data stored in the CGRect data structure. 

Apple advises the programmer to use CGGeometry functions like CGRectGetMinX and CGRectGetMinY, for example, to find the origin (and size) of elements instead of accessing size and position properties directly.

Now the programmer might facepalm their forehead at this point and proclaim, 'yet another thing to do!' but in reality CGGeometry is something worth knowing, because it opens the door to a range of interesting methods like CGRectIntersectsRect for detecting when one view intersects or overlaps another, and the related CGRectIntersection.


Endorse on Coderwall

Comments