0

I have a UIView that a user can add subviews to. I now need the application to automatically place a subview for the user at the first found open location.

A location is considered open if the frame of the subview to be placed does not intersect any other subviews.

The calculation to locate this open area does not need to be instant - it will run when the user first enters a scene, at which point it saves that location as if it were the user that placed it.

The container UIView will be large enough to ALWAYS have an open space to place the subview (there are a limited number of subviews that the user can add).

What would be the simplest way to determine a location to place the subview?

Alec Sanger
  • 4,442
  • 1
  • 33
  • 53

2 Answers2

0

Not quite sure whether there exist inbuilt method to do so. But you can run iterative loop and get bounds of all the view inside the container view. based on readings you will have to calculate open space.

slonkar
  • 4,055
  • 8
  • 39
  • 63
0

I posted a description of an algorithm commonly used to solve these sorts of problems in an answer to this question: Finding Largest Rectangle in 2D Array. It's fairly easy to adapt that solution to your problem. In the that question the filled spaces were on a grid, this made determining the amount to advance the scan line a little easier, you will have to be more careful. Also the other question was looking for the empty rectangle with the maximal area, you can exit the algorithm early as soon as you find a first fit.

Of course, if all your subviews are the same size, then the solutions are almost identical.

Hope this helps.

Community
  • 1
  • 1
idz
  • 12,825
  • 1
  • 29
  • 40