1

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)
   }
 }
APC
  • 144,005
  • 19
  • 170
  • 281
MJJLAM
  • 163
  • 1
  • 13
  • 2
    Your code doesn't make sense. The first pass through, rect1 will be uninitialized. Where does the starting value of rect1 come from? – Duncan C Jan 12 '16 at 21:29

2 Answers2

6

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) }
Cristik
  • 30,989
  • 25
  • 91
  • 127
  • 4
    Using contains() instead of reduce() might be more effective, as it stops the iteration once an intersection is found. – Martin R Jan 12 '16 at 21:38
  • Hmm... that would be clearly more effective, and more readable. Thanks for the suggestion. – Cristik Jan 12 '16 at 21:40
  • I don't know why, but almost always `reduce` come first into my mind; maybe I got too fund of reducers/transducers :P – Cristik Jan 12 '16 at 21:44
1

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...!