Thursday 4 September 2014

You are probably confused about Frames and Bounds!

Frames and Bounds have a learning curve of their own, if you do not have anyone to guide you about them. I learnt them the harder way. So that's why i want to make it simpler for people to understand them. Let us first have a look at the formal definitions of theirs. 

  • Frame: The frame property contains the frame rectangle, which specifies the size and location of the view in its superview’s coordinate system.
  • Bounds: The bounds property contains the bounds rectangle, which specifies the size of the view (and its content origin) in the view’s own local coordinate system. 
These are definitions according to the Apple's View Programming Guide. But what does these mean???

Well to begin with let's see what this magical statement does:
      [myView addSubview:anotherView];
This adds anotherView as myView's subview. Does this mean that we have told our system where to place this anotherView in my myView's coordinate system? NO!!!!
To set the position of your subview you need to use Bounds! Bounds will tell the subview to set its coordinates within its superview.

Let's say your myView's frame is (x=20,y=20,width=200,height=200).
And you do this:
anotherView.frame = myView.frame;   //This is completely wrong
This would place anotherView at origin (20,20) with respect to its superview.

What you probably wanted to do was 
anotherView.frame = myView.bounds; //Purrfect!

So when adding subview's to your view always use bounds (read as Boundary) to draw your subview in. Frame is basically for setting the position w.r.t. superview. 

At last 2 images to help you understand stuff better:



Hope this helps someone!

No comments:

Post a Comment