Tim Vermeulen
Tim Vermeulen

Reputation: 12562

Comparing two CGRects

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?

Upvotes: 100

Views: 33032

Answers (4)

zumzum
zumzum

Reputation: 20168

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

Upvotes: 2

Julian
Julian

Reputation: 9337

In the Swift 3 it would be:

frame1.equalTo(frame2)

Upvotes: 6

James Sumners
James Sumners

Reputation: 14787

See the documentation for CGRectEqualToRect().

bool CGRectEqualToRect ( CGRect rect1, CGRect rect2 );

Upvotes: 40

Amelia777
Amelia777

Reputation: 2674

Use this:

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

Upvotes: 258

Related Questions