János
János

Reputation: 35128

tableView vs. scrollView behavior when keyboard appears

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

Upvotes: 0

Views: 695

Answers (2)

Manisha
Manisha

Reputation: 181

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

Upvotes: 0

Imran
Imran

Reputation: 2941

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
}

Upvotes: 1

Related Questions