Introduction to Cocoa Autolayout
Cocoa Autolayout was introduced along with Mac OS X 10.7 Lion and Xcode 4.1. In short, Cocoa Autolayout replaces the old springs and struts model and introduces constraints based on intent. For example, this NSTextField must always stay x pixels away from this NSDatePicker.
This new API has two major benefits for localization:
- Localization by just swapping strings, no need to adjust XIBs in most cases
- UI mirroring for right-to-left languages, such as Arabic and Hebrew
In essence, Autolayout works by defining relationships and constraints. Let’s take the a widely used update window (Sparkle or otherwise) as an example. Most applications will offer three buttons, “Skip this version”, “Remind me later” and “Install” and the buttons will be sized to fit the English text. In previous versions of Xcode, the window would look something like this:
After receiving your translated strings from a translator, your XIB may then look something like this (Italian):
You can instantly see that the text is squashed into the buttons. Italian is a relatively concise language and you can imagine what German would look like. Even so, the current layout does not comply with Apple’s HIG rules so a bit of manual adjustment is required to fix this.
The problem isn’t limited to languages which are commonly associated with being longer than English, though this is often the problem case for developers. Japanese and Chinese are often remarkably concise and can result in a lot of white space. Again, not conforming to Apple’s HIGs.
This all changes with Cocoa Autolayout. There’s no need to open up each individual XIB in each localized language anymore as your application will now dynamically adjust the position and size of your buttons (and of course other elements) at runtime. It goes further by limiting itself to certain constraints to avoid objects overlapping or dominating the view. In the example above, the button “Remind Me Later” would in fact resize itself to fit “Ricordami più tardi” in realtime, making sure the distance between other objects remains in line with Apple’s HIGs.
Here’s what the result looks like, without any XIB customizing at all. Autolayout automatically resizes the NSButtons to fit the text and give the appropriate amount of padding as specified by the HIGs: