Reputation: 368
If you need more details: I have UICollectionViewCell which is draggable. When the cell overlaps other cells during dragging I want to know which one it overlaps mostly in order to replace overlapped cell with this cell. Is there any efficient way to do this? I found nothing helpful in CGGeometry. Thank you.
Upvotes: 0
Views: 128
Reputation: 4728
You can use CGRectUnion() in a loop, the one with a smallest area will be the one with the greatest overlap. You could write a function that deals with (and returns a) CGRects, but youd probably need to loop though your views (cells) again to find the correct one, so I'd keep it UIView level... Eg
//helpers
CGFloat CGRectGetArea(CGRect theRect){
return theRect.size.width * theRect.size.height;
}
-(UIView *)viewClosestToView:(UIView*)keyView fromViews:(NSArray*)comparisonViews{
UIView *result=nil;
CGFloat smallestArea=0.0;
for (UIView *view in comparisonViews){
CGFloat area = CGRectGetArea( CGRectUnion(view.frame, keyView.frame) );
if ((area < smallestArea)|| ((NSInteger)smallestArea==0) ){
smallestArea=area;
result=view;
}
}
return result;
}
Upvotes: 1
Reputation: 2993
Use CGRectIntersection(r1,r2) to find the intersection rect (if any). Multiply width and height of the returned rectangle to get the area. Compare the 4 areas to find the largest.
This should be way more than fast enough for UI manipulation.
Upvotes: 1