Comparing two CGRects
Asked Answered
B

4

99

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

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?

Baptism answered 13/10, 2012 at 22:12 Comment(0)
D
257

Use this:

if (CGRectEqualToRect(self.view.frame, rect)) {
     // do some stuff
}
Deci answered 16/9, 2013 at 3:44 Comment(0)
P
40

See the documentation for CGRectEqualToRect().

bool CGRectEqualToRect ( CGRect rect1, CGRect rect2 );
Presidio answered 13/10, 2012 at 22:41 Comment(0)
R
6

In the Swift 3 it would be:

frame1.equalTo(frame2)
Rathenau answered 19/6, 2017 at 16:11 Comment(1)
in fact, equalTo(_:) is now deprecated so == is preferred.Modify
W
2

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
Ware answered 22/8, 2018 at 22:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.