0

If a textfield opens keyboard and textfield is member of a tableView, then it will be able to scroll tableView to be able to see the last item, and keyboard will not hide that item.

enter image description here

How? UITableView is inherited from UIScrollView. I guess opening keyboard increases the content offset? Am I right?

If textfield is part of a scrollView, not a tableView, this effect will not occur, and it keyboard can hide out other controls positioned lower parts of the scrollView.

If I want to see the same effect with scrollView as with tableView, should I set content offset manually?

enter image description here

János
  • 27,206
  • 24
  • 130
  • 270
  • Hey Janos maybe you also find more helpful answers and insights here: http://stackoverflow.com/questions/1126726/how-to-make-a-uitextfield-move-up-when-keyboard-is-present – Geralt Sep 30 '15 at 14:27

2 Answers2

1

Yes you have to set your content offset manually .

First you register for the notification

NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name:UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name:UIKeyboardWillHideNotification, object: nil)

And then in your observer methods.

func textFieldShouldReturn(textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}

func keyboardWillShow(notification:NSNotification){

    var userInfo = notification.userInfo!
    var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()
    keyboardFrame = self.view.convertRect(keyboardFrame, fromView: nil)

    var contentInset:UIEdgeInsets = self.scrollView.contentInset
    contentInset.bottom = keyboardFrame.size.height
    self.scrollView.contentInset = contentInset
}

func keyboardWillHide(notification:NSNotification){

    var contentInset:UIEdgeInsets = UIEdgeInsetsZero
    self.scrollView.contentInset = contentInset
}
Imran
  • 2,898
  • 16
  • 32
  • Beside I am setting `contentInset`, can I set `contentSize` too? They are independent right? – János Sep 30 '15 at 08:59
0

You can import TPKeyboardAvoiding class downloaded from https://github.com/michaeltyson/TPKeyboardAvoiding and set the UITableView class to TPKeyboardAvoidingTableView.

Manisha
  • 151
  • 1
  • 4