iOS Custom Keyboard Autolayout

1k Views Asked by At

What constraints should I add in Interface Builder to a custom keyboard to act exactly like built in one when the user changes orientation like in the images below (All the buttons stretch horizontally and shrink vertically with equal spaces between them).

enter image description here

1

There are 1 best solutions below

1
On BEST ANSWER

This is pretty easy (if you know how to do autolayout).

So first of all, just drag the buttons(or UIView) you'd like to have to the background view. And manually layout them like what you wanted.

And I would start with the first row (Q~P), constraints could be setup like this

Q -> leading space to container: 4px

P -> trailing space to container: 4px

Q-W, W-E, E-R, R-T, T-Y, Y-U, U-I, I-O, O-P all has horizontal space like 4px

The interesting part is to determine the width, simply let Q-W, W-E, E-R, R-T, T-Y, Y-U, U-I, I-O, O-P have equal width. Why are we setting this constraint? Because once you fixed the Q leading, P trailing and all the gaps, setting them to be equal width will automatically let all the first row buttons to equally share the rest of the keyboard width (which is our button width). Forgot to mention, WERTYUIOP should center y to Q.

Now you just determined the first row with button width.

How do you determine the height? The idea is the same, the total keyboard height is comprised of the top margin(the gap on top of Q) and the bottom margin (the gap below space, or 123), the gap between rows and 4 * button height.

So, you can setup constraints like this, use Q, A, Z and 123 to determine the button height.

Q -> top space to container: 4px 123 -> bottom space to container: 4px Q-A, A-Z, Z-123, all have vertical space 4px and then set their height to be equal just like what we did for button width.

Then you can add constraints to W-P, to have equal height with Q (we just determined height for Q, A, Z, 123).

Now the first row is properly determined, next we consider the second row. We need a reference base for the x position of second row, you can maybe add constraint to G for center horizontally to container view, then setup the gaps for all the buttons in second row to be the same as first row(in this example, 4px). now you have 2nd row determined.

For the 3rd row, its really easy, you just need to position each button with the 2nd row. For example,

Z -> center x to S -> equal width to S

Remember that we have determined the y position and height for Z, so no need to do that anymore. For X-M, center them to Z for y, center them to 2nd row button for x, equal width to 2nd row button and equal height to Z.

I hope you get the idea, the major part of autolayout is to find the BASE, you need to have a starting point to start with so that all elements know where they should be as the container view size changes.

Hope this helps.