Comparing two CGRects
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
CGRect comparison appears in many UIKit tasks, including collision checks, layout verification, hit testing, and animation logic. The right comparison method depends on what you mean by match, overlap, or containment. This guide covers equality, intersection, containment, and tolerance-based comparisons with practical Swift examples.
Equality Comparison
If you need exact geometry equality, compare CGRect values directly.
Exact equality is useful in deterministic layout code, but small floating-point differences can make equal-looking rectangles fail this check.
Compare with Tolerance for Floating Values
For animation and transformed coordinates, use epsilon tolerance.
Tolerance checks are more stable when values come from transforms, scaling, or interpolation.
Intersection and Overlap Checks
To detect whether rectangles overlap, use intersects.
To compute the overlap region, use intersection.
This is useful for clipping, visible-area calculations, and collision response.
Containment Checks
Containment answers whether one rectangle fully includes another.
You can also test whether a point lies inside a rectangle.
Containment checks are common in gesture handling and drag constraints.
Coordinate Space Matters
Two rectangles from different coordinate systems are not directly comparable. Convert views into a shared coordinate space before comparing.
Always normalize coordinate space first for reliable overlap and equality logic.
Practical Layout Debug Pattern
When debugging layout regressions, print key rectangle values and compare expected against actual.
Pair this with assertions in unit tests for deterministic, repeatable UI geometry validation.
Use Integral Rectangles for Pixel Alignment
On some UI paths, tiny fractional coordinates can cause blurry rendering. If your comparison depends on visual alignment, normalize rectangles first.
Comparing normalized rectangles can reduce false mismatches in snapshot tests and layout assertions. Keep in mind that integral conversion changes geometry, so use it only for rendering-oriented checks, not physical collision logic.
Common Pitfalls
- Using exact equality for floating-point values that should use tolerance.
- Comparing rectangles from different coordinate spaces.
- Confusing overlap with containment in collision logic.
- Ignoring zero-width or zero-height rectangles that can affect intersection checks.
- Assuming transformed view bounds match displayed frame without conversion.
Summary
- Use direct equality only when exact matches are expected.
- Use epsilon-based comparison for float-heavy geometry.
- Use
intersectsandintersectionfor overlap logic. - Use
containsfor full enclosure checks. - Normalize coordinate spaces before any rectangle comparison.

