Finding free space in UIView


When there is a need to find free space in the UIView to add any subview, we can do this using CAShapeLayer and UIBezierPath.

  1. Create a CAShapeLayer for your main view where you will be adding sub views. Let's call it as main shape layer. This will be helpful to check the new view estimated is within the main view.
  2. Create a UIBezierPath instance. Whenever a valid new sub view is found, add the edges to this path.
  3. Create a random point within the main view.
  4. Create a CGRect based on random point as center of your sub view. Let’s call it as estimated view frame.
  5. Check the estimated view frame is completely visible in your main view. Else go to step 3.
  6. Check your 4 edges of your estimated view frame with path object. If any one of the edge is inside the path, go to step 3.
  7. If 4 edges are not inside the path, the estimated view frame is the new view’s frame.
  8. Create a new subview and add it to your main view.
  9. Add the edges of new view to path.
You can change the width and height of new view. I have added a condition to stop looking for next free space after trying 50 times. This will help to avoid infinite loop.
Limitations:
Taking a random number to add new view will waste the space and you will run out of space quickly. If you are able to maintain the free available space, you can add more sub views.


Comments

Popular posts from this blog

Swift - Strings

What's new in Swift 4!

Swift - Classes