Check to see if a CGRect intersects with an array of CGRects

1.1k Views Asked by At

I'm trying to see if a CGRects intersects with any other CGRects in an array before initializing the CGRect, but I am yet to find a fool proof method that works.

Note that intersection is the array of CGRects. Any takes on how to do this? The method below doesn't work sometimes the generated CGRect intersects with one in the array I'm not sure what I'm missing.

for element in intersection {
  while CGRectIntersectsRect(rect1, element) {
    xTemp = CGFloat(arc4random_uniform(UInt32(screenSize.width - buttonWidth1)))
    yTemp = CGFloat(arc4random_uniform(UInt32(screenSize.height - buttonWidth1)))
    rect1 = CGRect(x: xTemp, y: yTemp, width: buttonWidth, height: buttonWidth)
   }
 }
2

There are 2 best solutions below

3
On BEST ANSWER

You could make use of CGRectIntersectsRect:

let doesIntersect = arrayOfRects.reduce(false) {
    return $0 || CGRectIntersectsRect($1, testRect)
}

Or (thanks to Martin R for his suggestion), you could use the contains method instead of reduce:

let doesIntersect = arrayOfRects.contains { CGRectIntersectsRect($0, testRect) }
0
On

Swift 3.0:

let rectToCompare: CGRect! // Assign your rect here
for index in 0..<self. arrayOfRects.count {
  let rect = self. arrayOfRects[index]
  if rect.intersects(rectToCompare) {
     // Write your logic here
  }
}

Happy Coding...!