Reputation: 183
I'm trying to see if a CGRect
s intersects with any other CGRect
s 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 CGRect
s. 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)
}
}
Upvotes: 1
Views: 1168
Reputation: 186
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...!
Upvotes: 1
Reputation: 32783
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) }
Upvotes: 6