skip to Main Content

The secret getter methods of CGRect that are available since iOS 2.0

I saw in several tutorials and code snippets that iOS developers are still not using several methods that are available since iOS 2.0. I didn’t know about these CGRect iOS getter methods for several projects and thousands of lines of source codes until I realised that I could use them.

Usual problems are:

Trying to get the width of a view, so you use the following:

And now the easy way:

 

Which makes this line:

A lot shorter:

 

And you can use the following getters too to get different dimensions and distances between views:


How to use these CGRect getter methods of iOS, I cannot image…?

And if you need something to help you imagine this, here is a little help for you:

CGRect getter methods geometry guides

You might ask, and why should I use them? Especially the width snippet, it has almost the same width in characters than the normal method. Well that’s true, but at the end your code looks cleaner, easier to read and maintain in the future. Try them and you’ll notice a speed increase in your development for sure. Especially when you are using the CGRectGetMidX or MaxX getters, since you don’t have to do weird calculations, just pass in the frame and you get the value that you wanted.

For more information look at Apple’s documentation about CGRect and CGRectGeometry: documentation

  • Thanks for the post. I’m one of the novices that just bought Meng’s book and hope to start playing around very soon with Swift. Still setting up my programming environment etc. This will possibly come in handy for me. Looking forward to seeing more tips in the future.

    Geoff

    • You’re welcome. Keep coming back to the site, we will post new tricks and tutorials regularly. 😉

  • Aashish Tyagi

    Nice blog 🙂