New comers to iOS development usually get confused by a UIView having two different properties to represent its position and size. Namely ‘bounds’ and ‘frame’. Surprisingly, many senior iOS devs can’t explain in clear terms the difference between the two either. So I thought I would try to explain in simpler words the difference between the two.
UIView — An infinite sheet:
An instance of UIView always has a height, and a width. But to clearly understand the difference between bounds and frame, we first need to revisit our visualisation of a UIView instance. Think of a UIView as an infinite sheet, that is divided into four quadrants, just like a cartesian coordinate plane. However, a regular cartesian coordinate plane has its y-axes increasing towards the top. While our UIView plane’s y-axes increases downwards, and has negative values upwards. Just like a regular cartesian plane, our UIView plane has its centre at point (0, 0).
Even though a UIView can be thought of as infinite sheet, and we can add subviews to it anywhere in this infinite space, we only get to see a finite section of this infinite sheet at a given time. And this is where bounds and frame come into play.
Bounds define a finite window into the infinite sheet of UIView. At any given time, we only see the contents of the view that lie within the bounds of this view. Any content that is part of the view, but lying outside the bounds won’t appear (or would appear if it is within the bounds of the superview and view doesn’t have its clipsToBounds set to YES, but won’t receive touches). If we change the position and size of bounds to move to another portion of the infinite sheet of view, content at that location would start to appear.
Thus, bounds is a window into an infinite sheet of content that is UIView.
Frame is the location and size of a UIView instance within its superview. Thus if we don’t change frame, but change bounds, view would show different contents, but at the same location within the superview. If we change frame, and keep bounds the same, view would show the same content but at a different location within the superview.
Remember that frame and bounds have same size values, but their origin values can differ.
Bounds is view’s location and size within its own coordinate system. Frame is views location and size within superview’s coordinate system.