Bounds and Center

Suppose we wish to give a view a subview inset by 10 points, as in Figure 14-3. The utility function CGRectInset makes it easy to derive one rectangle as an inset from another, but what rectangle should we use as a basis? Not the superview’s frame; the frame represents a view’s position within its superview, and in that superview’s coordinates. What we’re after is a CGRect describing our superview’s rectangle in its own coordinates, because those are the coordinates in which the subview’s frame is to be expressed. That CGRect, describing a view’s rectangle in its own coordinates, is the view’s bounds property.

A subview inset from its superview
Figure 14-3. A subview inset from its superview

So, the code to generate Figure 14-3 looks like this:

UIView* v1 = [[UIView alloc] initWithFrame:CGRectMake(113, 111, 132, 194)];
v1.backgroundColor = [UIColor colorWithRed:1 green:.4 blue:1 alpha:1];
UIView* v2 = [[UIView alloc] initWithFrame:CGRectInset(v1.bounds, 10, 10)];
v2.backgroundColor = [UIColor colorWithRed:.5 green:1 blue:0 alpha:1];
[self.window.rootViewController.view addSubview: v1];
[v1 addSubview: v2];

You’ll very often use a view’s bounds in this way. When you need coordinates for drawing inside a view, whether drawing manually or placing a subview, you’ll often refer to the view’s bounds.

Interesting things happen when you set a view’s bounds. If you change a view’s bounds size, you change its

Get Programming iOS 6, 3rd Edition 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.