Prevent a UIView from Overflow outside SuperView in Swift

2.3k Views Asked by At

Let's say there is UIView(0,0,100,100) which has two SubViews, one is (-5,-5,10,10) and second is (0,95,10,10). I want to let first SubView overflow from superView but not secondOne. Is there any property in UIView which I can set to prevent a UIView from overflowing it's SuperView? Or what is the best way to achieve this?

NOTE: Here co-ordinates are in form of (x,y,Width,Height)

UPDATE: As some people have marked this question unclear, let me add some bullet points for same:

  1. I am familiar with clipToBounds property of UIView, But that will let all of it's subViews to be clipped, But my question was vise-versa.
  2. I Just wanted to know if there is any property in UIView which will prevent a UIView of overflow from it's superView.
  3. To state same problem I just gave an example in which setting clipToBounds to superView will not serve our purpose because one subView needs to be overflow from it's parent View.

Please let me know in comments if it's still unclear.

2

There are 2 best solutions below

2
On BEST ANSWER

There is a property called clipsToBounds, but it works vice versa - it tells a UIView that all it's subviews are clipped to not be drawn outside of it's own bounds.

Therefore in your case if you wan't to have one View that goes out of bounds, and one that do not, you will need additional(transparent) view that will have same rect as superview, but will clip subviews.

Then add your clipping subview as child of this new transparent layer, and the other one should be direct child to the superview.

Hope this helps :)

1
On

You can set clipToBounds property of your UIView to true. when you set clipToBounds to yes, its subview will not overflow.