How does clipsToBounds work?

Viewed 83256

I would like to know how to use the UIView property clipsToBounds.

The official documentation says the following:

clipsToBounds property

A Boolean value that determines whether subviews are confined to the bounds of the view.

Discussion
Setting this value to YES causes subviews to be clipped to the bounds of the receiver. If set to NO, subviews whose frames extend beyond the visible bounds of the receiver are not clipped. The default value is NO.

But I'm unclear on what this means exactly. How should I be using clipsToBounds? What are the consequences of setting this property to YES exactly? Or to NO?

2 Answers

If Apple was to rename this property, I'd name it: clipSubviewsToBounds.

Why?

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.

enter image description here

Related