11

I have a UITableView with 7 cells and every cell has a text field inside it. When the keyboard appears it hides the last cell so it is quite difficult to see what has been input until and unless the keyboard disappears.

Can anyone guide me how I can scroll this UITableview up when the keyboard appears so I don't have this problem?

shim
  • 9,289
  • 12
  • 69
  • 108
neena
  • 365
  • 1
  • 6
  • 22
  • 2
    A tableview is just a UIScrollView subclass, the answer provide in the official documentation can be used https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html#//apple_ref/doc/uid/TP40009542-CH5-SW1 – Andrea Dec 16 '15 at 15:40
  • This was in objective-c . I have a swift version now, if anyone needs it in future. NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWasShown:"), name:UIKeyboardDidShowNotification, object: nil); NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil); – neena Dec 16 '15 at 16:02
  • 1
    and then the function body like this:func keyboardWasShown(sender: NSNotification) { let info:NSDictionary = sender.userInfo! let kbSize:CGSize = (info.objectForKey(UIKeyboardFrameBeginUserInfoKey)?.CGRectValue.size)! let contentInsets:UIEdgeInsets = UIEdgeInsetsMake(0.0,0.0,kbSize.height,0.0) tableView.contentInset = contentInsets tableView.scrollIndicatorInsets = contentInsets } – neena Dec 16 '15 at 16:06
  • 1
    func keyboardWillHide(sender: NSNotification) { let contentInsets:UIEdgeInsets = UIEdgeInsetsZero; tableView.contentInset = contentInsets; tableView.scrollIndicatorInsets = contentInsets; } – neena Dec 16 '15 at 16:07
  • The best solution ever is you can find here : https://github.com/michaeltyson/TPKeyboardAvoiding. – iDevAmit Sep 09 '16 at 03:28

2 Answers2

6

Try this one:

func textFieldDidBeginEditing(textField: UITextField) {
    tableView.setContentOffset(CGPointMake(0, textField.center.y-60), animated: true)
}
shim
  • 9,289
  • 12
  • 69
  • 108
Ayush Yadav
  • 294
  • 5
  • 11
0

Use thiese simple set of classes https://github.com/michaeltyson/TPKeyboardAvoiding

How to use:

For use with UITableViewController classes, drop TPKeyboardAvoidingTableView.m and TPKeyboardAvoidingTableView.h into your project, and make your UITableView a TPKeyboardAvoidingTableView in the xib. If you're not using a xib with your controller, I know of no easy way to make its UITableView a custom class: The path of least resistance is to create a xib for it.

iAnurag
  • 9,286
  • 3
  • 31
  • 48