Simple keyboard/text field interaction handling on iOS

EDITED TO ADD 5:15 PM PST I updated the gist because I realized I wanted to have a block run whenever I finished adjusting the view and therefore I added a completionBlock property. I'm using this to scroll a UITableView that contains text fields: whenever the keyboard finishes adjusting then I scroll the UITableView so the cell being edited is at the bottom. It works pretty well!


RoadTrip has a couple of places where if you hold the phone in landscape the keyboard can cover up a text field you're trying to edit. It's always struck me as weird that iOS can't handle this for you automatically but it doesn't, so there's a little weird piece of code you have to write to rearrange views somehow. In both places in RoadTrip I wanted to do the same thing: simply slide the main view upwards so that the field being edited is just over the top of the keyboard. I even wrote a comment saying that I should make this code some sort of generic solution, but I never went back to do so.

While working on 1.6 I noticed that the new predictive text bar on iOS 8 caused a problem with that code, so I patched it up. While doing that I noticed that the API for keyboard position changes does something other than the documentation does: if you ask for the notification curve you're supposed to get a UIViewAnimationCurve enum but sometimes you get 7, which is really a bitfield you can assign to the proper parts of the UIViewAnimationOptions. General consensus on the web seems to be to just take the "UIViewAnimationCurve", bitshift it up 16 places, and slam it into the UIViewAnimationOptions but that seems awful fragile to me.

Anyway, I fixed it up for RoadTrip, made another mental note to extract that code and submitted it.

Yesterday was the day I really did. I rewrote it into Swift and made a simple little widget that you can just create, feed it a view, and it watches for the keyboard notifications. It's a pretty simple class overall and I threw up a gist with the source. Take a look if that sounds like something you'd like to have. It uses my logger, but you can easily remove those calls.

I'm not sure what the deal is with the damn HeaderDoc comments. Sometimes they work for me in Xcode's Quick Help, sometimes they don't and I can't find anything that makes a difference. If anybody knows how to use HeaderDoc to make comments in Swift framework code that works reliably in both Objective-C and Swift let me know. I can't find anything about it.