此答案基于您不使用视图的假设,而是您正在处理包含不同矩形区域的模型。
您只需遍历框列表,并使用该功能BOOL CGRectContainsPoint(rect, point);
例如(假设您的矩形被装箱在 NSValues 中,存储在 NSArray 中):
NSArray* arrayOfRects = ...;
CGPoint point = CGPointMake(xTouch, yTouch);
CGRect rectResult = CGRectNull;
for (NSValue* rectObj in arrayOfRects) {
CGRect rect = [rectObj CGRectValue];
if (CGRectContainsPoint(rect, point)) {
rectResult = rect;
break;
};
}
if (!CGRectEqualToRect(rectResult, CGRectNull)) {
// Found a matching rect!
}
else {
// Touch was outside of any recognised rect
}
此解决方案不会处理重叠的矩形。如果你需要这个,你需要保留一组匹配项,如下所示:
NSArray* arrayOfRects = ...;
CGPoint point = CGPointMake(xTouch, yTouch);
NSMutableArray* rectResultArray = [NSMutableArray array];
for (NSValue* rectObj in arrayOfRects) {
if (CGRectContainsPoint([rectObj CGRectValue], point)) {
[rectResultArray addObject:rectObj];
};
}
if (rectResultArray.count > 0) {
// Found matching rects!
}
else {
// Touch was outside of any recognised rect
}