How frames work on macOS

Christoffer Winterkvist
3 min readFeb 26, 2018

--

Annie Spratt — https://unsplash.com/photos/hS46bsAASwQ

Even if constraints are pretty much the default for building UI on macOS/iOS and tvOS, there are still situations when frames are the preferable choice. Frame manipulation on macOS is very similar to its counterparts; you work with CGRect’s, you’ll see references to NSRect but under the hood that is just a type alias for CGRect. However, there is one fundamental difference, the coordinate system is flipped, or rather, it is flipped on iOS and tvOS.
What this means is that an x-coordinate with the value of zero starts at the bottom of its super view and not at the top. Worth noting is that this only affects the x-coordinate, y-coordinates works like you would expect.

If you are used to calculating frames on iOS and tvOS, wrapping your head around doing everything in reverse can be a challenge. Luckily, Apple introduced a property for us to override whenever we want to flip the coordinate system so that an x-coordinate or zero means the top of the subview.

Let’s have a quick look at what that could look like in a very simple NSView example.

Here we create two NSView’s, one container and one view that takes color. For the sake of demonstrating how it works, the container inherits from ColorView so that the container can also get a color.

As you can see from the image, the subview is positioned in the lower left corner. With just one line of code, we can reverse the container view to get the desired behavior.

As you can see, we only added an override of isFlipped and set that to return true. Let’s see what the documentation has to say about the isFlipped property.

The default value of this property is false, which results in a non-flipped coordinate system. In a non-flipped coordinate system, the origin is in the lower-left corner of the view, and positive y-values extend upward. In a flipped coordinate system, the origin is in the upper-left corner of the view and y-values extend downward. X-values always extend to the right.

If you want your view to use a flipped coordinate system, override this property and return true.

https://developer.apple.com/documentation/appkit/nsview/1483532-isflipped

So by overriding the property, anything inside that views coordinate system will now be flipped. Be sure to note that adding additional subviews to an underlying subview will not inherit this and will have to override the same method if you want those also to be flipped.

To illustrate what I mean, let’s look at one final example.

Example 3

That’s it, no more headaches when doing frame based calculations on macOS.

--

--

Christoffer Winterkvist

random hero at @fink-oslo by day, cocoa vigilante by night, dad at dawn. my life is awesome. Previously @hyperoslo