Bhavesh Sachala
Bhavesh Sachala

Reputation: 19

IQKeyboardManager scrolls whole screen but want to scroll only tableview content

In My Chatting App textFieldDidBeginEditing adds keyboard height automatic using IQKeyboardManager but it scrolls whole screen to top. I have a requirement to only scroll tableView's content. My navigationBar should stay attached to top but using third party scroll library (IQKeyboardManager) scrolls all part in top. So How can I only scroll the tableView content?

Upvotes: 0

Views: 2335

Answers (1)

Ratnesh Jain
Ratnesh Jain

Reputation: 681

In your ChatViewController you can disable IQKeyboardManager.

override func viewWillAppear(_ animated: Bool) {
   super.viewWillAppear(animated)
   IQKeyboardManager.shared().isEnabled = false
   IQKeyboardManager.shared().isEnableAutoToolbar = false
}

You can re-enable it when you are about to leave that view-controller like this.

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    IQKeyboardManager.shared().isEnabled = true
    IQKeyboardManager.shared().isEnableAutoToolbar = true
}

Now that we are disabling IQKeyboardManager we have to manage the keyboard our-selves.

To do that you can try below approach.

override func viewDidLoad() {
    super.viewDidLoad()
    prepareTableView()
    observeKeyboardEvents()
}

Here you call the observeKeyboardEvents method in viewDidLoad method.

private func observeKeyboardEvents() {
    NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: nil) { [weak self] (notification) in
        guard let keyboardHeight = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return }
        print("Keyboard height in KeyboardWillShow method: \(keyboardHeight.height)")
        self?.tableView.contentInset.bottom = keyboardHeight.height + 8
        self?.tableView.scrollIndicatorInsets.bottom = keyboardHeight.height + 8
        }

     NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: nil) { [weak self] (notification) in
         self?.tableView.scrollIndicatorInsets.bottom = 0 + 8
         self?.tableView.contentInset.bottom = 0 + 8
     }
}

In observeKeyboardEvents method, you register this view-controller to observe the Keyboard Appear and Disappear notifications and adjust your tableView's contentInset.bottom accordingly. So we should also remove this view-controller to stop receiving keyboard events notification. For that you can try below code.

deinit {
    NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
    NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
}

Hope, this might help you. :)

Upvotes: 1

Related Questions