Mahir
Mahir

Reputation: 1684

How to test if one UIView is being touched by another UIView?

I have a custom UIView, holder.

I have another custom UIView from a different class, and the instance is named letter.

When letter touches holder, i want holder to respond.

Upvotes: 0

Views: 1797

Answers (1)

Tim
Tim

Reputation: 60130

You can check that the intersection of the two views' frames is null. Use the frame method on the UIView class to get the CGRect frame of each view, then call CGRectIntersection to find the rectangles' overlapping area, if any. If they don't touch, the intersection will be the null rectangle (i.e. will return true for CGRectIsNull).

Code, untested:

// Given UIView * letter, * holder:
CGRect letterFrame = [letter frame];
CGRect holderFrame = [holder frame];
CGRect intersection = CGRectIntersection(letterFrame, holderFrame);
if(CGRectIsNull(intersection)) {
    // Not touching yet - null intersection
} else {
    // Touching! Do something here
}

Upvotes: 5

Related Questions