Skip to content

Using Autolayout to Imitate the Apple Keyboard

archagon edited this page Oct 3, 2014 · 1 revision

Is it possible to duplicate Apple's iPhone keyboard using just a single autolayout configuration? The answer is "almost". Let's take the lowest row of the US keyboard with the default button configuration. There are four buttons: character set change, keyboard change, spacebar, and return.

[picture 1]

You'll notice that the character set change button and the keyboard change button are the same size. This applies regardless of keyboard type and orientation, so we can add this as a constraint. The next question is, how do we define the size of these buttons? One way is to tie them to the width of the superview. Autolayout gives us a multiplier and a constant to work with, which means that given two example values, we can always find an autolayout constraint to match them.

Using linear algebra, it's quite easy to figure out the equation that we need to use. When the width is 568, we know that the buttons are 50 wide; and when the width is 320, we know that the buttons are 34 wide. So:

568m + b = 50
320m + b = 34
50 - 568m = 34 - 320m
m = (34 - 50)/(568 - 320)
b = 50 - 568m

We can then bind the button widths to the superview with those variables and everything works.

But wait! There's a small problem.

If we also consider the iPhone 4, at 480px wide, we find out that the button width is 41px. Unfortunately, our equation results in a button width of 44px. D'oh!

So it seems that Apple uses different autolayout constraints between portrait and landscape mode. (Actually, they probably just use manual values, but I haven't checked.) Question is, is it worth the hassle to support the correct pixel value for the iPhone 4s? After all, a) it's going to be deprecated very soon, and b) 44 is close enough to 41 in practice. Personally, I think the benefit of having a single autolayout constraint system for both portrait and landscape beats out accuracy in this regard, especially as we move to different iPhone sizes in the future.

Clone this wiki locally