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?

Tim Vermeulen
  • 12,352
  • 9
  • 44
  • 63

4 Answers4

257

Use this:

if (CGRectEqualToRect(self.view.frame, rect)) {
     // do some stuff
}
Johannes Fahrenkrug
  • 42,912
  • 19
  • 126
  • 165
Amelia777
  • 2,664
  • 2
  • 16
  • 11
40

See the documentation for CGRectEqualToRect().

bool CGRectEqualToRect ( CGRect rect1, CGRect rect2 );
Stunner
  • 12,025
  • 12
  • 86
  • 145
James Sumners
  • 14,485
  • 10
  • 59
  • 77
6

In the Swift 3 it would be:

frame1.equalTo(frame2)
Julian
  • 9,299
  • 5
  • 48
  • 65
  • 2
    in fact, `equalTo(_:)` is now [deprecated](https://developer.apple.com/documentation/coregraphics/cgrect/1456516-equalto) so `==` is preferred. – olx May 09 '18 at 05:51
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
zumzum
  • 17,984
  • 26
  • 111
  • 172