Skip to content

Instantly share code, notes, and snippets.

@Abhishek9634
Created July 20, 2020 18:35

Revisions

  1. Abhishek9634 created this gist Jul 20, 2020.
    35 changes: 35 additions & 0 deletions KeyboardNotification.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@

    extension ViewController {

    private func setupKeyboardNotifications() {
    NotificationCenter.default.addObserver(self,
    selector: #selector(keyboardWillShow(_:)),
    name: UIResponder.keyboardWillShowNotification,
    object: nil)

    NotificationCenter.default.addObserver(self,
    selector: #selector(keyboardWillHide(_:)),
    name: UIResponder.keyboardWillHideNotification,
    object: nil)
    }

    @objc
    private func keyboardWillShow(_ sender: Notification) {
    guard let info = sender.userInfo,
    let frame = (info[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {
    return
    }

    self.bottomConstraint.constant = frame.size.height
    UIView.animate(withDuration: 0.3) {
    self.view.layoutIfNeeded()
    }
    }

    @objc
    private func keyboardWillHide(_ sender: Notification) {
    self.bottomConstraint.constant = 0
    self.view.layoutIfNeeded()
    }

    }