2

I need help to make my chat ViewController behave like Whatsapp does when you open and close your keyboard. That means: If the keyboard is opened, the view moves up. If it is closed, it returns to the original position.

What I already have: My chat ViewController has a ContainerView and below that ContainerView is a TextField. I have set up two observers which are catching UIKeyboardWillShow and UIKeyboardWillHide. The ContainerView and the TextField both have constraints at the top, left, right and bottom. between them is a vertical spacing.

What I've tried: I took the bottom constraint of the TextField and added the height of the keyboard to it. It moves correctly.

Where I need help: The TableView inside the ContainerView does not move correctly with the TextField. Here are some screenshots that show my problem: https://i.stack.imgur.com/EdcyN.jpg

it looks like the keyboard is overlaying the ContainerView. But it seems like the TableView inside the ContainerView is messing it up.

I expect "thank you for reading the example messages" to be shown when I click the TextField, but it gets cut. I thought about scrolling down to the bottom everytime you open the keyboard, but that would not work if you look into the middle of the chat and try to type something, you want to stay exactly where you are looking at.

Thank you for reading through this and thanks for any help!

Jochen Österreicher
  • 683
  • 2
  • 11
  • 25

1 Answers1

2

There are two ways to do what you are trying to accomplish:

  1. programmatically modify the bottom constraint constant to include the height of the keyboard. This will pin the bottom of your tableview to the top.

  2. The method I would use is just adding a content inset to your tableview equal to the height of the keyboard. This approach is more simple because it does not require you modifying view constraint constants.

Start like this:

override func viewDidLoad(){
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardShow), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
}

func keyboardShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0)
    }
}

func keyboardHide(notification: NSNotification) {
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
}

Note that if you want to push the content up to the bottom of the textfield, add your textfield height to your keyboard height.

thexande
  • 1,645
  • 16
  • 23