views:

3940

answers:

1

UIView and its subclasses all have the properties "frame" and "bounds". What's the difference? (don't quote apple docs)

Thanks!!

+16  A: 

The frame of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to the superview it is contained within.

The bounds of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to its own coordinate system (0,0).

So, imagine a view that has a size of 100x100 (width x height) positioned at 25,25 (x,y) of its superview. The following code prints out this view's bounds and frame:

// This method is in the view controller of the superview
- (void)viewDidLoad {
    [super viewDidLoad];

    NSLog(@"bounds.origin.x: %f", label.bounds.origin.x);
    NSLog(@"bounds.origin.y: %f", label.bounds.origin.y);
    NSLog(@"bounds.size.width: %f", label.bounds.size.width);
    NSLog(@"bounds.size.height: %f", label.bounds.size.height);

    NSLog(@"frame.origin.x: %f", label.frame.origin.x);
    NSLog(@"frame.origin.y: %f", label.frame.origin.y);
    NSLog(@"frame.size.width: %f", label.frame.size.width);
    NSLog(@"frame.size.height: %f", label.frame.size.height);
}

And the output of this code is:

bounds.origin.x: 0
bounds.origin.y: 0
bounds.size.width: 100
bounds.size.height: 100

frame.origin.x: 25
frame.origin.y: 25
frame.size.width: 100
frame.size.height: 100

So, we can see that in both cases, the width and the height of the view is the same regardless of whether we are looking at the bounds or frame. What is different is the x,y positioning of the view. In the case of the bounds, the x and y coordinates are at 0,0 as these coordinates are relative to the view itself. However, the frame x and y coordinates are relative to the position of the view within the parent view (which earlier we said was at 25,25).

There is also a great presentation that covers UIViews. See slides 1-20 which not only explain the difference between frames and bounds but also show visual examples.

shek
So won't the x,y for bounds always be 0,0 since its the location of the object in... itself. Or could you give a scenario where it wouldn't be?
Mk12
As far as I know, the origin of the bounds will always be 0,0
shek
Ok thanks, I think I understand it better now.
Mk12
Actually, the bounds.origin can be something besides 0,0. Use setBoundsOrigin: to move/translate the origin. See "View Geometry" in the "View Programming Guide for Cocoa" for more info.
Meltemi
Learn something new each day. +1 to you sir.
shek
UIScrollView is an example where the bounds can shift to show different content regions within a view.
Brad Larson