比较两个 CGRect

我需要检查我的视图框架是否等于给定的 CGRect。我试过这样做:

CGRect rect = CGRectMake(20, 20, 20, 20);
if (self.view.frame == rect)
{
// do some stuff
}

但是,我在说 Invalid operands to binary expression('CGRect' (aka 'struct CGRect') and 'CGRect')时出错了。为什么我不能简单地比较两个 CGRect呢?

31848 次浏览

See the documentation for CGRectEqualToRect().

bool CGRectEqualToRect ( CGRect rect1, CGRect rect2 );

Use this:

if (CGRectEqualToRect(self.view.frame, rect)) {
// do some stuff
}

In the Swift 3 it would be:

frame1.equalTo(frame2)

In Swift simply using the == or != operators works for me:

    let rect = CGRect(x: 0, y: 0, width: 20, height: 20)


if rect != CGRect(x: 0, y: 0, width: 20, height: 21) {
print("not equal")
}


if rect == CGRect(x: 0, y: 0, width: 20, height: 20) {
print("equal")
}

debug console prints:

not equal
equal