I’ve created a custom UIView with a subview containing several square subviews which are sized using layout constraints. I’d like for each subview to be circular so I’m holding a reference to the view in an array, then iterating through the array of views in the layoutSubviews method and applying a corner radius that is half the view.bounds.height.
The problem is, this only works 70% of the time. Sometimes the view doesn’t seem to know its bounds and the views are rendered as square.
I’m probably approaching this all wrong… does anyone have any advice for me? Where is it safe to apply the corner radius so that it always renders as a perfect circle?
Thanks
3
Answers
You can apply the corner radius inside the
layoutSubviews()
methodThe most reliable way to manage this is to subclass
UIView
and let it handle its own rounding.For example:
This simple controller example:
Produces this output:
No need to iterate through subviews and setting values based on frame sizes… all you need to do is set the size/position constraints.
Donmag’s example is cool.Also, you can do it this way without writing code to layoutsubview. You must add this settings
after adding the constraints
of the subviews infor iteration
.