MJJLAM MJJLAM - 1 year ago 90
iOS Question

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

I'm trying to see if a

s intersects with any other
s in an array before initializing the
, but I am yet to find a fool proof method that works.

Note that intersection is the array of
s. Any takes on how to do this? The method below doesn't work sometimes the generated
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)

Answer Source

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) }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download