16

I can't find where I read it, but I remember coming across something that suggested it is better to access height of CGRects using CGRectGetHeight(rect) instead of accessing the variable via rect.size.height

CGFloat height = CGRectGetHeight(self.frame);
// vs  
CGFloat height = self.frame.size.height;

Most of the time, this has to do with views in my use, and I was wondering if there is a real difference (apart from syntax) that separates these two lines of code.

If one is preferential over the other, an explanation of why would be great!

Avt
  • 16,927
  • 4
  • 52
  • 72
Logan
  • 52,262
  • 20
  • 99
  • 128

1 Answers1

20

CGRect structures might store height and width in negative values and CGRectGetHeight will always return the positive one. In Swift 3.0 CGRect.height property should be used instead of CGRectGetHeight.

CGRect.height

Regardless of whether the height is stored in the CGRect data structure as a positive or negative number, this function returns the height as if the rectangle were standardized. That is, the result is never a negative number.

Avt
  • 16,927
  • 4
  • 52
  • 72
  • That was it, I couldn't remember why it said! Thanks! I'll accept in 10 mins. (when it lets me) – Logan May 07 '14 at 21:22
  • More generically, from the [CGGeometry reference](https://developer.apple.com/library/mac/documentation/graphicsimaging/reference/CGGeometry/Reference/reference.html): “All functions described in this reference that take `CGRect` data structures as inputs implicitly standardize those rectangles before calculating their results. For this reason, your applications should avoid directly reading and writing the data stored in the `CGRect` data structure. Instead, use the functions described here to manipulate rectangles and to retrieve their characteristics.” – Zev Eisenberg May 07 '14 at 21:46
  • In Xcode 8.2.1 using `CGRectGetHeight` results in a compliation error: “_CGRectGetHeight' has been replaced by property ‘CGRect.height’_”. – RobertJoseph Mar 21 '17 at 12:15
  • CGRectGetHeight in Swift is CGRect.height. Eg. view.frame.height – iOS Nepal Apr 05 '18 at 07:18