ios 比较两个 CGRects

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12877496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 20:44:49  来源:igfitidea点击:

Comparing two CGRects

iosobjective-ccocoa-touchcomparisoncgrect

提问by Tim Vermeulen

I needed to check wether the frame of my view is equal to a given CGRect. I tried doing that like this:

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

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

However, I got an error saying Invalid operands to binary expression('CGRect' (aka 'struct CGRect') and 'CGRect'). Why can't I simply compare two CGRects?

但是,我收到一个错误说Invalid operands to binary expression('CGRect' (aka 'struct CGRect') and 'CGRect'). 为什么我不能简单地比较两个CGRects?

回答by Amelia777

Use this:

用这个:

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

回答by James Sumners

See the documentationfor CGRectEqualToRect().

请参阅CGRectEqualToRect()的文档

bool CGRectEqualToRect ( CGRect rect1, CGRect rect2 );

回答by Julian Król

In the Swift 3 it would be:

在 Swift 3 中,它将是:

frame1.equalTo(frame2)

回答by zumzum

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

在 Swift 中,只需使用==or!=运算符对我有用:

    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