Bounds and Center

Suppose we wish to give a view a subview inset by 10 pixels, 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 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 addSubview: v1];
[v1 addSubview: v2];
[v1 release]; [v2 release];

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.

Note

The screen also has bounds, and functions in that sense as the window’s superview, even though a UIScreen isn’t a view. Moreover, the window’s frame is always ...

Get Programming iOS 4 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.