The code for keyboard handling could be improved, I found the following issues:
(bug) The padding is too large when keyboard is shown on phones with safe areas. The problem is that the keyboard height includes the safe area padding, but the view pads from the safe area.
I submit a solution where the bottom safe area edge is ignored if keyboard is shown.
(improvement) The way the KeyboardFollower is passed to the view — I think that the use of @EnvironmentObject is much better, you will probably use the KeyboardFollower in multiple views in an app. Instead of passing around one or many instances of KeyboardFollower it’s much better to create one instance serving the complete app.
(improvement) The KeyboardFollower implementation. Why not just start the observing when the class in init’ed? The code will be much cleaner, no need for subscribe/unsubscribe in the class, and each view does not need to have .onAppear/.onDisappear handlers clogging down the code.
(bug) If two views is using the same instance of current KeyboardFollower implementation, the first view disappearing will disable further notifications to the remaining view.
This is my suggested code improvements (a working example):
@audrey
(bug) I found another issue with the KeyboardFollower implementation.
If you have the keyboard visible while leaving the app for another app (or springboard) the reported height is wrong when coming back to the app again.
I tried your suggestion, but I couldn’t notice any visible difference - but your idea seems a good one, so I’ll test it again in the future.
I agree, but also disagree :]. The reason is that I prefer the keyboard follower to not be shared - I think that each view should have its own instance, so that’s why I chose to not pass it as an env object.
Another good suggestion. I’ve just improved your implementation a little bit, by unsubscribing in deinit
That’s one of the reasons why I prefer not not share the keyboard follower. :]
You right - and your fix works!
Thank you very much for your help. Your suggestions and fixes will be available in the next book version.
I’m working thru this book now with Swift 5.3 and Xcode 12.2. The view seems to adjust itself automatically when the keyboard appears, without using KeyboardFollower. Are they handling this automatically now?