How To Adjust Views To Fit the Keyboard in iOS

Using NSLayoutConstraint subclasses

Adam Wareing
Better Programming

--

Adjusting view size on phone
Photo by the author.

With a scrollable view — whether that’s a UITableView, UIScrollView, or even a UIView — when the keyboard appears, it takes up space and typically means you have to adjust your view to be dynamically responsive depending on the keyboard’s visibility.

The most common way of handling this is using the NotificationCenter to respond to the following events:

UIResponder.keyboardWillHideNotification
UIResponder.keyboardWillChangeFrameNotification

This works, but you have to add code in every class that uses a keyboard to handle it. One option proposed by Hacking with Swift is:

This works brilliantly, and there is nothing wrong with it. However, let’s see if there is another way of handling it.

My preference is to have my UIView and UIViewController’s logic as specific as possible to that view and to abstract common logic out where possible. I find that it improves the readability of the code and increases the speed at which you can understand an unfamiliar class.

Introducing NSLayoutConstraint Subclasses

This is where subclassing an NSLayoutConstraint becomes useful. Placing all of the logic for expanding and contracting based on whether the keyboard is showing or hiding allows us to simply set a constraint and not have to worry about handling the logic for it.

If you use AutoLayout, then you can simply set the class to be the subclassed variant in your project, as shown below:

Setting class to be subclass

Alternatively, you can create the constraint programmatically, although my preference is to use AutoLayout where appropriate.

The only downside to this approach is that if someone were eventually to replace this constraint with a non-subclassed constraint, it would break the view. With that said, something like that should be found by the developer or, at worst, caught with a good testing practice. I believe the upside to this approach far outweighs the downsides.

Below is my variant of the subclass, which is a modification of one created by Meng To that you are more than welcome to use in your projects:

That’s it! Thanks for reading this article. Hopefully, it has taught you something new.

--

--