Comparing two CGRects

IosObjective CCocoa TouchComparisonCgrect

Ios Problem Overview


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?

Ios Solutions


Solution 1 - Ios

Use this:

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

Solution 2 - Ios

See the documentation for CGRectEqualToRect().

bool CGRectEqualToRect ( CGRect rect1, CGRect rect2 );

Solution 3 - Ios

In the Swift 3 it would be:

frame1.equalTo(frame2)

Solution 4 - Ios

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTim VermeulenView Question on Stackoverflow
Solution 1 - IosAmelia777View Answer on Stackoverflow
Solution 2 - IosJames SumnersView Answer on Stackoverflow
Solution 3 - IosJulianView Answer on Stackoverflow
Solution 4 - IoszumzumView Answer on Stackoverflow