just recreated your project and seems to be working nice for me testing on an iPhone 7 plus.
The collection view scrolls and reveals the textfield. Now one issue is that the padding below the keyboard is not always the same. My suggestion in your case is to make sure you have the constraints for your textfield in place and try again. That might make a difference.
On the other hand, I would suggest to use a ScrollView instead of a collection view.
Collection views have cell reuse which might cause problems to you in terms of cells been reused and textfields being deallocated.
What I usually do when having a form with lots of TextFields is the following:
- Create a scrollView and pin to all the edges. Especially the bottom constraint is important
- Add view in the scrollView pin it to all the edges and make the width and height of your inclosed UIView equal to the width and height of the ScrollViews superview. (That way the scroll insets will scale correctly)
- Add your textFields as Subviews to the UIView above
- Add observers for keyboard notifications in your UIViewController and animate the bottom constraint of the scrollView to the height of the keyboard and back to 0 when the keyboard moves a way from the screen.
That way you make sure that you control the screen animations and you can add more padding if you feel necessary. The scrollView will handle the resisting and get your textField placed in the correct viewport.
Furthermore, you will be able to have references to all of your textFields. Either by creating outlets or by adding them to an OutletCollection.
I usually do the latter in order to keep them in order and move the focus to the next one on the list.
import UIKit
class KeyboardViewController: UIViewController {
@IBOutlet weak var bottomScrollViewConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
@IBAction func hideKeyboard(_ sender: Any) {
self.view.endEditing(true)
}
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
self.bottomScrollViewConstraint.constant = keyboardSize.height //Add more padding here if you want
UIView.animate(withDuration: 0.8, animations: {
self.view.layoutIfNeeded()
})
}
}
func keyboardWillHide(notification: NSNotification) {
self.bottomScrollViewConstraint.constant = 0
UIView.animate(withDuration: 0.8, animations: {
self.view.layoutIfNeeded()
})
}
}
