If my superview is a box measuring 10 units on each side, and my subview is 20 units wide, with clipsToBounds
set to YES
, I'll only see the part of the subview that fits within the bounds of the superview. Otherwise, if clipsToBounds
is set to NO
, I'll see the entire subview, even the parts outside the superview (assuming we're still on the screen).
As a visual example, consider the following views set up on the storyboard:
This is a white UIView
, a label in the top left corner with either a simple "1" or "2" so that I can discuss these as view1
or view2
. Additionally, the black view is the same size as the white view, but it's origin is at the white view's center.
In the view controller's viewDidLoad
method, we have the following code:
- (void)viewDidLoad {
[super viewDidLoad];
self.view1.clipsToBounds = YES;
self.view2.clipsToBounds = NO;
}
override func viewDidLoad() {
super.viewDidLoad()
self.view1.clipsToBounds = true
self.view2.clipsToBounds = false
}
When we run the code and look at in the simulator or on the device, we get the following results:
So, despite these views being set up identically (except clipsToBounds
), they look different. This is what clipsToBounds
does. Setting it to YES
will provide the top result, while setting it to NO
provides the bottom result.
If we debug the view hierarchy, we can see more clearly that the black boxes both do actually extend past the boarders of the white view, but only view 2 shows this when the app is actually running:
This is meant to be a succinct quick answer vs. the accepted answer
If Apple was to rename this property, I'd name it: clipSubviewsToBounds
.
I just ran into a bug in our code. Where the parent view's height was set to 0
.
We expected to see none of its elements/subviews. Yet parent view's subviews were showing up.
It was because clipToBounds
wasn't set to true
. Once that's set to true
then the subviews heights can't extend beyond 0
, they get clipped to once they reach the height of its superview. In this case they'll get clipped at 0
ie they don't show at all.
Having this insight is helpful when you're debugging your view using Xcode's 'Debug View Hierarchy' . As you can then select Show clipped content and see if a subview is getting clipped to the bounds of its superview. e.g. if your subview has a width of 250 but the super has only 200, then once you toggle this you will see the extra 50 points that are getting clipped/hidden.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With