clipsToBounds in Swift

Swarandeep Singh Sran
3 min readMar 10, 2023

--

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

Setting this value to true causes subviews to be clipped to the bounds of the view. If set to false, subviews whose frames extend beyond the visible bounds of the view aren’t clipped. The default value is false. Some subclasses of UIView, like UIScrollView, override the default value to true.

Let us understand this with help of an example. Create a new Xcode project. Place a UIView in the centre of screen. Give it some constraints and a colour (brown in this case) to make it appear distinct.

Initial Setup
The Constraints that I have applied on the brown view

Create IBOutlet of brown view and actually name it brownView. Now add the following code to viewDidLoad method and then run the app.

brownView.layer.cornerRadius = 40

We get the following Output

The corners get rounded.

Now add a new UIView inside brownView and give (0,0,0,0) constraints to it with brownView as shown here.

Now run the app again.

We notice that redView has no corner radius. But why? It is inside brownView and we have given cornerRadius to brownView, and hence it should have cornerRadius.

When we give a view rounded corners in an iOS app, we may notice that the view looks rounded but any content inside it (like images or text) spills over the edges of the rounded corners. Setting clipsToBounds to true on the view ensures that the content inside the view is also cut off at the rounded corners, making everything look neat and tidy. It's like cutting a photo to fit into a picture frame - if the photo is too big, we cut off the edges so it fits nicely.

Now add this line in viewDidLoad and re-run the app

brownView.clipsToBounds = true
Final Output

If you found this article helpful, kindly share this story, follow me on medium and give applaud 👏. Thank You!

--

--

No responses yet