我正在尝试实现检查视图是否是另一个视图的边界来做某事。这是我的代码:
CGRect movingView = [self.viewController.view convertRect:recognizer.view.frame toView:self.viewController.view];
for (NSUInteger i = 0; i < arrayOfViewsToCheck.count; i++)
{
UIView *view = resultArray [0];
CGRect boxframe = [self.viewController.view convertRect:view.frame toView:self.viewController.view];
if (CGRectIntersectsRect(movingView.frame, view.frame) )
{
isInBounds = YES;
}
}
但是当我执行我的代码时,例如我有两个观点:
(CGRect) $6 = origin=(x=569, y=513) size=(width=76, height=100)
(CGRect) $7 = origin=(x=358, y=520) size=(width=116, height=100)
是彼此的界限,但每个人都不知道我做错了什么,因为看起来他们不在我的代码上。
我真的很感激,如果可以,请让我知道我在做错了,试图检测视图是否在彼此的范围内
答案 0 :(得分:2)
您对CGRectIntersectsRect
的使用是正确的,但示例中的矩形实际上并不相交。这是他们的样子:
- (void)viewDidLoad
{
[super viewDidLoad];
CGRect rect1 = CGRectMake(569,513,76,100);
CGRect rect2 = CGRectMake(368,520,116,100);
UIView *view1 = [[UIView alloc] initWithFrame:rect1];
UIView *view2 = [[UIView alloc] initWithFrame:rect2];
view1.backgroundColor = [UIColor redColor];
view2.backgroundColor = [UIColor blueColor];
[self.view addSubview:view1];
[self.view addSubview:view2];
}
稍加修改版本:
- (void)viewDidLoad
{
[super viewDidLoad];
CGRect rect1 = CGRectMake(469,513,76,100); /* Note 469 instead of 569 */
CGRect rect2 = CGRectMake(368,520,116,100);
UIView *view1 = [[UIView alloc] initWithFrame:rect1];
UIView *view2 = [[UIView alloc] initWithFrame:rect2];
view1.backgroundColor = [UIColor redColor];
view2.backgroundColor = [UIColor blueColor];
[self.view addSubview:view1];
[self.view addSubview:view2];
if (CGRectIntersectsRect(rect1, rect2) ) {
NSLog(@"Yay we intersect!");
}
}