Apple’s Geometry API

One cool function I recently learned about is CGRectUnion. CGRectUnion can be used to determine the size of the rectangle needed to encompass a pair of source rectangles. CGRectUnion is part of Apple’s Geometry class which contains such favorites as CGRectGet[Min|Max|Mid][x|y] for finding the min, max and mid points of a given view. CGRectUnion can be extremely useful for calculating the size of a bounding rectangle needed to enclose a group of views. Apple’s documentation states that CGRectUnion returns “The smallest rectangle that completely contains both of the source rectangles.”

For example, lets say that you wanted to find the size of a rectangle to enclose a view controller’s subviews. With CGRectUnion this is a trivial exercise.

Here we enumerate the view controller’s subviews (the red, blue, and green views) and calculate the size of the rectangle need to encompass all the subviews. We then create a new view based on that bounding rectangle and insert it at the beginning of the view hierarchy. In the examples shown, the yellow view is the bounding rectangle created.

One important point to remember/consider is Apple’s new UILayoutGuides which are added to a standard UIViewController class created in storyboard. This can cause issues with calculating the size of a bounding rect, since it will contain two UIView objects which have CGRectZero attribute. We can find and exclude these views by looking for views that conform to the protocol UILayoutSupport.

Like what you read? Give Dennis Walsh a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.