[cocoa] Cocoa: What's the difference between the frame and the bounds?

UIView and its subclasses all have the properties frame and bounds. What's the difference?

This question is related to cocoa cocoa-touch uiview

The answer is


Frame vs bounds

  • If you create a view at X:0, Y:0, width:400, height:400, its frame and bounds are the same.
  • If you move that view to X:400, its frame will reflect that change but its bounds will not. Remember, the bounds is relative to the view’s own space, and internally to the view nothing has changed.
  • If you transform the view, e.g. rotating it or scaling it up, the frame will change to reflect that, but the bounds still won’t – as far as the view is concerned internally, it hasn’t changed.
  • If you change the bounds then it will change the content inside the frame because the origin of the bounds rectangle starts at a different part of the view.

All answers above are correct and this is my take on this:

To differentiate between frame and bounds CONCEPTS developer should read:

  1. relative to the superview (one parent view) it is contained within = FRAME
  2. relative to its own coordinate system, determines its subview location = BOUNDS

"bounds" is confusing because it gives the impression that the coordinates are the position of the view for which it is set. But these are in relations and adjusted according to the frame constants.

iPhone screen


Short Answer

frame = a view's location and size using the parent view's coordinate system

  • Important for: placing the view in the parent

bounds = a view's location and size using its own coordinate system

  • Important for: placing the view's content or subviews within itself

Detailed Answer

To help me remember frame, I think of a picture frame on a wall. The picture frame is like the border of a view. I can hang the picture anywhere I want on the wall. In the same way, I can put a view anywhere I want inside a parent view (also called a superview). The parent view is like the wall. The origin of the coordinate system in iOS is the top left. We can put our view at the origin of the superview by setting the view frame's x-y coordinates to (0, 0), which is like hanging our picture in the very top left corner of the wall. To move it right, increase x, to move it down increase y.

To help me remember bounds, I think of a basketball court where sometimes the basketball gets knocked out of bounds. You are dribbling the ball all over the basketball court, but you don't really care where the court itself is. It could be in a gym, or outside at a high school, or in front of your house. It doesn't matter. You just want to play basketball. In the same way, the coordinate system for a view's bounds only cares about the view itself. It doesn't know anything about where the view is located in the parent view. The bounds' origin (point (0, 0) by default) is the top left corner of the view. Any subviews that this view has are laid out in relation to this point. It is like taking the basketball to the front left corner of the court.

Now the confusion comes when you try to compare frame and bounds. It actually isn't as bad as it seems at first, though. Let's use some pictures to help us understand.

Frame vs Bounds

In the first picture on the left we have a view that is located at the top left of its parent view. The yellow rectangle represents the view's frame. On the right we see the view again but this time the parent view is not shown. That's because the bounds don't know about the parent view. The green rectangle represents the view's bounds. The red dot in both images represents the origin of the frame or bounds.

Frame
    origin = (0, 0)
    width = 80
    height = 130

Bounds 
    origin = (0, 0)
    width = 80
    height = 130

enter image description here

So the frame and bounds were exactly the same in that picture. Let's look at an example where they are different.

Frame
    origin = (40, 60)  // That is, x=40 and y=60
    width = 80
    height = 130

Bounds 
    origin = (0, 0)
    width = 80
    height = 130

enter image description here

So you can see that changing the x-y coordinates of the frame moves it in the parent view. But the content of the view itself still looks exactly the same. The bounds have no idea that anything is different.

Up to now the width and height of both the frame and the bounds have been exactly the same. That isn't always true, though. Look what happens if we rotate the view 20 degrees clockwise. (Rotation is done using transforms. See the the documentation and these view and layer examples for more information.)

Frame
    origin = (20, 52)  // These are just rough estimates.
    width = 118
    height = 187

Bounds 
    origin = (0, 0)
    width = 80
    height = 130

enter image description here

You can see that the bounds are still the same. They still don't know anything has happened! The frame values have all changed, though.

Now it is a little easier to see the difference between frame and bounds, isn't it? The article You Probably Don't Understand frames and bounds defines a view frame as

...the smallest bounding box of that view with respect to it’s parents coordinate system, including any transformations applied to that view.

It is important to note that if you transform a view, then the frame becomes undefined. So actually, the yellow frame that I drew around the rotated green bounds in the image above never actually exists. That means if you rotate, scale or do some other transformation then you shouldn't use the frame values any more. You can still use the bounds values, though. The Apple docs warn:

Important: If a view’s transform property does not contain the identity transform, the frame of that view is undefined and so are the results of its autoresizing behaviors.

Rather unfortunate about the autoresizing.... There is something you can do, though.

The Apple docs state:

When modifying the transform property of your view, all transformations are performed relative to the center point of the view.

So if you do need to move a view around in the parent after a transformation has been done, you can do it by changing the view.center coordinates. Like frame, center uses the coordinate system of the parent view.

Ok, let's get rid of our rotation and focus on the bounds. So far the bounds origin has always stayed at (0, 0). It doesn't have to, though. What if our view has a large subview that is too big to display all at once? We'll make it a UIImageView with a large image. Here is our second picture from above again, but this time we can see what the whole content of our view's subview would look like.

Frame
    origin = (40, 60)
    width = 80
    height = 130

Bounds 
    origin = (0, 0)
    width = 80
    height = 130

enter image description here

Only the top left corner of the image can fit inside the view's bounds. Now look what happens if we change the bounds' origin coordinates.

Frame
    origin = (40, 60)
    width = 80
    height = 130

Bounds 
    origin = (280, 70)
    width = 80
    height = 130

enter image description here

The frame hasn't moved in the superview but the content inside the frame has changed because the origin of the bounds rectangle starts at a different part of the view. This is the whole idea behind a UIScrollView and it's subclasses (for example, a UITableView). See Understanding UIScrollView for more explanation.

When to use frame and when to use bounds

Since frame relates a view's location in its parent view, you use it when you are making outward changes, like changing its width or finding the distance between the view and the top of its parent view.

Use the bounds when you are making inward changes, like drawing things or arranging subviews within the view. Also use the bounds to get the size of the view if you have done some transfomation on it.

Articles for further research:

Apple docs

Related StackOverflow questions

Other resources

Practice yourself

In addition to reading the above articles, it helps me a lot to make a test app. You might want to try to do something similar. (I got the idea from this video course but unfortunately it isn't free.)

enter image description here

Here is the code for your reference:

import UIKit

class ViewController: UIViewController {


    @IBOutlet weak var myView: UIView!

    // Labels
    @IBOutlet weak var frameX: UILabel!
    @IBOutlet weak var frameY: UILabel!
    @IBOutlet weak var frameWidth: UILabel!
    @IBOutlet weak var frameHeight: UILabel!
    @IBOutlet weak var boundsX: UILabel!
    @IBOutlet weak var boundsY: UILabel!
    @IBOutlet weak var boundsWidth: UILabel!
    @IBOutlet weak var boundsHeight: UILabel!
    @IBOutlet weak var centerX: UILabel!
    @IBOutlet weak var centerY: UILabel!
    @IBOutlet weak var rotation: UILabel!

    // Sliders
    @IBOutlet weak var frameXSlider: UISlider!
    @IBOutlet weak var frameYSlider: UISlider!
    @IBOutlet weak var frameWidthSlider: UISlider!
    @IBOutlet weak var frameHeightSlider: UISlider!
    @IBOutlet weak var boundsXSlider: UISlider!
    @IBOutlet weak var boundsYSlider: UISlider!
    @IBOutlet weak var boundsWidthSlider: UISlider!
    @IBOutlet weak var boundsHeightSlider: UISlider!
    @IBOutlet weak var centerXSlider: UISlider!
    @IBOutlet weak var centerYSlider: UISlider!
    @IBOutlet weak var rotationSlider: UISlider!

    // Slider actions
    @IBAction func frameXSliderChanged(sender: AnyObject) {
        myView.frame.origin.x = CGFloat(frameXSlider.value)
        updateLabels()
    }
    @IBAction func frameYSliderChanged(sender: AnyObject) {
        myView.frame.origin.y = CGFloat(frameYSlider.value)
        updateLabels()
    }
    @IBAction func frameWidthSliderChanged(sender: AnyObject) {
        myView.frame.size.width = CGFloat(frameWidthSlider.value)
        updateLabels()
    }
    @IBAction func frameHeightSliderChanged(sender: AnyObject) {
        myView.frame.size.height = CGFloat(frameHeightSlider.value)
        updateLabels()
    }
    @IBAction func boundsXSliderChanged(sender: AnyObject) {
        myView.bounds.origin.x = CGFloat(boundsXSlider.value)
        updateLabels()
    }
    @IBAction func boundsYSliderChanged(sender: AnyObject) {
        myView.bounds.origin.y = CGFloat(boundsYSlider.value)
        updateLabels()
    }
    @IBAction func boundsWidthSliderChanged(sender: AnyObject) {
        myView.bounds.size.width = CGFloat(boundsWidthSlider.value)
        updateLabels()
    }
    @IBAction func boundsHeightSliderChanged(sender: AnyObject) {
        myView.bounds.size.height = CGFloat(boundsHeightSlider.value)
        updateLabels()
    }
    @IBAction func centerXSliderChanged(sender: AnyObject) {
        myView.center.x = CGFloat(centerXSlider.value)
        updateLabels()
    }
    @IBAction func centerYSliderChanged(sender: AnyObject) {
        myView.center.y = CGFloat(centerYSlider.value)
        updateLabels()
    }
    @IBAction func rotationSliderChanged(sender: AnyObject) {
        let rotation = CGAffineTransform(rotationAngle: CGFloat(rotationSlider.value))
        myView.transform = rotation
        updateLabels()
    }

    private func updateLabels() {

        frameX.text = "frame x = \(Int(myView.frame.origin.x))"
        frameY.text = "frame y = \(Int(myView.frame.origin.y))"
        frameWidth.text = "frame width = \(Int(myView.frame.width))"
        frameHeight.text = "frame height = \(Int(myView.frame.height))"
        boundsX.text = "bounds x = \(Int(myView.bounds.origin.x))"
        boundsY.text = "bounds y = \(Int(myView.bounds.origin.y))"
        boundsWidth.text = "bounds width = \(Int(myView.bounds.width))"
        boundsHeight.text = "bounds height = \(Int(myView.bounds.height))"
        centerX.text = "center x = \(Int(myView.center.x))"
        centerY.text = "center y = \(Int(myView.center.y))"
        rotation.text = "rotation = \((rotationSlider.value))"

    }

}

Frame its relative to its SuperView whereas Bounds relative to its NSView.

Example:X=40,Y=60.Also contains 3 Views.This Diagram shows you clear idea.

FRAME

BOUNDS


Bounds - x:0, y:0, width: 20, height: 40 is a static
Frame - x:60, y:20, width: 45, height: 45 is a dynamic based on inner bounds.

One more illustration to show a difference between frame and bounds. At this example:

  • View B is a subview of View A
  • View B was moved to x:60, y: 20
  • View B was rotated 45 degrees

enter image description here


try to run the code below

- (void)viewDidLoad {
    [super viewDidLoad];
    UIWindow *w = [[UIApplication sharedApplication] keyWindow];
    UIView *v = [w.subviews objectAtIndex:0];

    NSLog(@"%@", NSStringFromCGRect(v.frame));
    NSLog(@"%@", NSStringFromCGRect(v.bounds));
}

the output of this code is:

case device orientation is Portrait

{{0, 0}, {768, 1024}}
{{0, 0}, {768, 1024}}

case device orientation is Landscape

{{0, 0}, {768, 1024}}
{{0, 0}, {1024, 768}}

obviously, you can see the difference between frame and bounds


The answers above have very well explained the difference between Bounds and Frames.

Bounds : A view Size and Location as per its own coordinate system.

Frame : A view size and Location relative to its SuperView.

Then there is confusion that in case of Bounds the X,Y will always be "0". This is not true. This can be understood in UIScrollView and UICollectionView as well.

When bounds' x, y are not 0.
Let's assume we have a UIScrollView. We have implemented pagination. The UIScrollView has 3 pages and its ContentSize's width is three times Screen Width (assume ScreenWidth is 320). The height is constant (assume 200).

scrollView.contentSize = CGSize(x:320*3, y : 200)

Add three UIImageViews as subViews and keep a close look at the x value of frame

let imageView0 = UIImageView.init(frame: CGRect(x:0, y: 0 , width : scrollView.frame.size.width, height : scrollView.frame.size.height))
let imageView1 :  UIImageView.init( frame: CGRect(x:320, y: 0 , width : scrollView.frame.size.width, height : scrollView.frame.size.height))
let imageView2 :  UIImageView.init(frame: CGRect(x:640, y: 0 , width : scrollView.frame.size.width, height : scrollView.frame.size.height))
scrollView.addSubview(imageView0)
scrollView.addSubview(imageView0)
scrollView.addSubview(imageView0)
  1. Page 0: When the ScrollView is at 0 Page the Bounds will be (x:0,y:0, width : 320, height : 200)

  2. Page 1: Scroll and move to Page 1.
    Now the bounds will be (x:320,y:0, width : 320, height : 200) Remember we said with respect to its own coordinate System. So now the "Visible Part" of our ScrollView has its "x" at 320. Look at the frame of imageView1.

  3. Page 2: Scroll and move to Page 2 Bounds : (x:640,y:0, width : 320, height : 200) Again take a look at frame of imageView2

Same for the case of UICollectionView. The easiest way to look at collectionView is to scroll it and print/log its bounds and you will get the idea.


frame is the origin (top left corner) and size of the view in its super view's coordinate system , this means that you translate the view in its super view by changing the frame origin , bounds on the other hand is the size and origin in its own coordinate system , so by default the bounds origin is (0,0).

most of the time the frame and bounds are congruent , but if you have a view of frame ((140,65),(200,250)) and bounds ((0,0),(200,250))for example and the view was tilted so that it stands on its bottom right corner , then the bounds will still be ((0,0),(200,250)) , but the frame is not .

enter image description here

the frame will be the smallest rectangle that encapsulates/surrounds the view , so the frame (as in the photo) will be ((140,65),(320,320)).

another difference is for example if you have a superView whose bounds is ((0,0),(200,200)) and this superView has a subView whose frame is ((20,20),(100,100)) and you changed the superView bounds to ((20,20),(200,200)) , then the subView frame will be still ((20,20),(100,100)) but offseted by (20,20) because its superview coordinate system was offseted by (20,20).

i hope this helps somebody.


The frame is the rectangle that defines the UIView with respect to its superview.

The bounds rect is the range of values that define that NSView's coordinate system.

i.e. anything in this rectangle will actually display in the UIView.


Let me add my 5 cents.

Frame is used by the view's parent view to place it inside the parent view.

Bounds is used by the view itself to place it's own content (like a scroll view does while scrolling). See also clipsToBounds. Bounds also can be used to zoom in/out content of the view.

Analogy:
Frame ~ TV screen
Bounds ~ Camera (zoom, move, rotate)


Examples related to cocoa

How to update a single pod without touching other dependencies How to initialise a string from NSData in Swift Input from the keyboard in command line application Get current NSDate in timestamp format Xcode build failure "Undefined symbols for architecture x86_64" Cocoa Autolayout: content hugging vs content compression resistance priority setValue:forUndefinedKey: this class is not key value coding-compliant for the key iOS - Build fails with CocoaPods cannot find header files Get Current date & time with [NSDate date] Remove all whitespaces from NSString

Examples related to cocoa-touch

Include of non-modular header inside framework module Move textfield when keyboard appears swift Create space at the beginning of a UITextField Navigation bar with UIImage for title Generate a UUID on iOS from Swift How do I write a custom init for a UIView subclass in Swift? creating custom tableview cells in swift How would I create a UIAlertView in Swift? Get current NSDate in timestamp format How do you add an in-app purchase to an iOS application?

Examples related to uiview

How can I mimic the bottom sheet from the Maps app? UIView touch event in controller Swift addsubview and remove it Swift UIView background color opacity How do I change UIView Size? How to add constraints programmatically using Swift Load a UIView from nib in Swift Remove all constraints affecting a UIView How do I write a custom init for a UIView subclass in Swift? How to use UIVisualEffectView to Blur Image?