Ios CGRECT有时不起作用

Ios CGRECT有时不起作用,ios,Ios,此方法有问题。我在情节提要中添加了三个视图。如下所示: 然后我编写了一些代码: if (CGRectContainsRect(self.redView.frame,self.blueView.frame)) { NSLog(@"redView contain blueView!"); } else { NSLog(@"redView not contain blueView!"); } if (CGRectContainsRect(self.redView.f

此方法有问题。我在情节提要中添加了三个视图。如下所示:

然后我编写了一些代码:

if (CGRectContainsRect(self.redView.frame,self.blueView.frame)) { 
    NSLog(@"redView contain blueView!");
} else {
    NSLog(@"redView not contain blueView!");       
}

if (CGRectContainsRect(self.redView.frame,self.yellowView.frame)) {
    NSLog(@"redView contain yellowView!");
} else {
    NSLog(@"redView not contain yellowView!");   
}

NSLog(@"%@ %@ %@",NSStringFromCGRect(self.redView.frame),NSStringFromCGRect(self.blueView.frame),NSStringFromCGRect(self.yellowView.frame));
 {{36, 74}, {240, 260}} {{8, 8}, {120, 120}} {{112, 135}, {120, 120}}
但结果是:redView不包含blueView!redView包含yellowView!
我只是想知道为什么redView不包含blueView?

示例中的坐标显示,红色框中实际上不包含蓝色框。这可能是因为这些视图不共享同一个superview。看起来蓝色视图是红色视图的子视图

你必须确保

  • 测试视图位于同一superview中
  • 或者在测试之前将它们的帧转换为相同的坐标系
如何转换矩形:

CGRect yellowRect = [self.yellowView convertRect:self.yellowView.bounds
                                          toView:self.redView];
if (CGRectContainsRect(self.redView.bounds, yellowRect)) {
    ...

谢谢你@Nikolai Ruhe。