I’m trying to move the content up when the keyboard appears. This is the content which is a simple login form.
Please note that these are not UITextField
s. Its just a small UITableView
in the middle of a UIViewController
. And I have a UIScrollView
filling the view controller embedding that table view.
I’ve registered for the keyboard notifications, UIKeyboardDidShowNotification
and UIKeyboardWillHideNotification
.
And in the method that fires when the keyboard appears, I've implemented a variation of this answer which does pretty much the same thing, setting the bottom
value of the UIEdgeInsets
which is used to set the contentInset
of the scroll view.
func keyboardWasShown(notification: NSNotification) {
var info: NSDictionary = notification.userInfo as NSDictionary
var keyboardSize: CGSize = info.objectForKey(UIKeyboardFrameBeginUserInfoKey).CGRectValue().size
let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0)
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
}
The problem is it doesn't do anything. I successfully get the height of the keyboard but nothing changes. Can anybody tell me why and what I should do to fix this please?
Thank you.
After much struggle, I was able to accomplish what I wanted. What I did was, in the viewDidLoad
I registered for the keyboard notifications. And when the keyboard appears, I got its frame in to a variable and the login form's (which is a table view) frame into another variable.
By using CGRectIntersection
I got the frame of the intersected portion when the keyboard overlaps the login form and go its height. Then I simply set it in scroll view's setContentOffset
method to automatically move the scroll view up. To move it back down to the original position I just set scroll view's contentOffset
property again to CGPointZero
.
func registerForKeyboardNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil)
}
func keyboardWasShown(notification: NSNotification) {
var info: NSDictionary = notification.userInfo as NSDictionary
var keyboardFrame: CGRect = info.objectForKey(UIKeyboardFrameEndUserInfoKey).CGRectValue()
var loginFormFrame: CGRect = self.view.convertRect(self.tableView.frame, fromView: nil)
var coveredFrame: CGRect = CGRectIntersection(loginFormFrame, keyboardFrame)
self.scrollView.setContentOffset(CGPointMake(0, coveredFrame.height + 20), animated: true)
}
func keyboardWillBeHidden(notification: NSNotification) {
self.scrollView.contentOffset = CGPointZero
}