UIScrollView with auto-layout solution for UITextField (keyboard)
2014-11-10 | Hits
I believe there are many people are facing this problem. Last time my approach was to change the the scrollView's contentSize upon keyboard appear, and restore to normal when keyboard dismiss.
Now the problem in auto layout of scrollView was the contentSize is based on it’s subviews. I have figured out a way to do that
In the case above, you have a UIScrollView in your ViewController, and a UITextField inside the UIScrollView.
I remention the problem here, when the textField on focus, the keyboard will brought up, and the scrollView's contentSize still the same,
the keyboard may blocked the textField and become invisible, yet it cannot scroll up.
Let’s begin to solve this
Declare 2 ivars, a dummy view & it’s height constraint.
Initialize all views, and make sure translatesAutoresizingMaskIntoConstraints is set to NO for all views that wanted to use auto layout.
Add constraints to all these view. The matrics is actually variables that wanted to use inside the constraints’ visual format.
Initialize the dummy view’s height constraint separately to that ivar. Since it is dummy, so set the height (refer the constant argument) to 0.
Remember to add keyboard’s notification (listen to keyboard’s event)
When the keyboard is shown, remove the dummy view’s constraint first, then set the dummy view’s height to keyboard’s height, then only add the height constraint back to the dummy view.
When keyboard is hide, do the same thing with 6, but the constant now is 0.