Swift: bounds vs frame
Have you ever made an iOS app with UIKit? Have you ever made your own views? Customized a user control or a view?
Then you have probably already been in contact with the frames and bounds. But how well do you know them? Do you really know the difference between the two?
I noticed that for many the answer was: No.
So let’s go back to these notions to learn more.
If we look at the documentation of the two properties, we notice that their declaration is identical except for the name :
Frame:
var frame: CGRect { get set }
Bounds:
var bounds: CGRect { get set }
Note that both properties return a structure of type CGRect. This one simply represents a rectangle in memory, that is to say 4 essential information: X, Y, width and height.
But then where is the difference?
If we look at the documentation of frame, it says this :
The frame rectangle, which describes the view’s location and size in its superview’s coordinate system.
Note the importance of the end of the sentence: its superview’s coordinate system. This is not at all what is specified for the other property:
The bounds rectangle, which describes the view’s location and size in its own coordinate system.
What does this mean in reality?
It’s quite simple really, the bounds will have the coordinates relative to itself and will therefore have an X and a Y always equal to 0. While the frame will take these coordinates relative to its parent in the view hierarchy.
It is therefore important to refer to the frame if you want to have the position of the view, the bounds does not know the hierarchy of the view.
However, for the width and height, you can look at either one or the other. When one value is updated, the other is also updated.