Swift: Which direction a UIView is being intersected from?

402 Views Asked by At

I am using CGRectIntersectsRect to test if blueView (being dragged) has intersected with redView (stationary). However, I need to know if redView was intersected by blueView from red's top, bottom, right or left? Is there a CG method to accomplish this?

2

There are 2 best solutions below

1
On BEST ANSWER

Here is the solution I finally used, In case someone else is looking for it. Below line of code test if the intersection is vertical (top & bottom views intersected), where a and b are view.frame for each of the two view intersecting.

if ((a.maxY > q.maxY) && (b.minY < q.minY)) || ((a.maxY < q.maxY) && (b.minY > q.minY))

0
On

I'm not aware of any CG Method to accomplish this.

The way I'd go about this is using CGRectIntersectsRect to check if they intersect at all, then if they do intersect, measure from the center of redView to blueView which would return the distance between them (X and Y), from that you could possibly tell from which angle the intersection was coming from?

If you wanted a little more accuracy you could measure from redView top center, to blueView bottom center, and the same for all 4 edges? Then work out which is the closest?

There are multiple ways you could approach this problem but I'm not aware of a 'one method fits all' solution.

Edit:

Was still thinking about this, I think the most accurate way would be something like this:

let leftDistance = blue.origin.x - (red.origin.x + red.width)
let rightDistance = (blue.origin.x + blue.width) - red.origin.x
let topDistance = blue.origin.y - (red.origin.y + red.height)
let bottomDistance = (blue.origin.y + blue.height) - red.origin.y

The the lowest of those distance = coming from the left, right, top or bottom.

(P.s. I might have gotten blue + Red the wrong way around, as well as top and bottom. I'd recommend just having a play around and logging these values while dragging the item)