NSNotificationCenter Swift 3.0 on keyboard show and hide
Asked Answered
L

10

20

I am trying to run a function when the keyboard shows and disappears and have the following code:

let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(ViewController.keyBoardUp(Notification :)), name:  NSNotification.Name.UIKeyboardWillShow, object: nil)

And the function keyBoardUp below:

func keyBoardUp( Notification: NSNotification){
    print("HELLO")
}

However the function doesn't print to the console when the keyboard shows. Help would be greatly appreciated

Lizarraga answered 18/1, 2017 at 11:41 Comment(3)
Change selector to #selector(ViewController.keyBoardUp(notification:)) and function to func keyBoardUp( notification: Notification){ print("HELLO") }Spaetzle
Possible duplicate of Swift 3 NSNotificationCenter Keyboardwillshow/hideSecco
In swift 3, shouldn't you be getting a compiler error at the function?Wretch
O
43

Swift 3:

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: Notification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: Notification.Name.UIKeyboardWillHide, object: nil)

}

func keyboardWillShow(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        print("notification: Keyboard will show")
        if self.view.frame.origin.y == 0{
            self.view.frame.origin.y -= keyboardSize.height
        }
    }

}

func keyboardWillHide(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y != 0 {
            self.view.frame.origin.y += keyboardSize.height
        }
    }
}

Swift 4.2.1:

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 fileprivate func keyboardWillShow(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        // Do something with size
    }
}

@objc fileprivate func keyboardWillHide(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        // Do something with size
    }
}

Swift 4.2+

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)

}

@objc func keyboardWillShow(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y == 0{
            self.view.frame.origin.y -= keyboardSize.height
        }
    }

}

@objc func keyboardWillHide(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y != 0 {
            self.view.frame.origin.y += keyboardSize.height
        }
    }
}
Obtect answered 18/1, 2017 at 12:50 Comment(3)
This code wil get fail , keyboard active ,type anyting , dont resign and press lock button of iphone and then little bit later unlock your iphone , your view will be not visiibleLeapfrog
I got around that by hardcoding the keyboardSize.height (since I didn't want to move the entire view by the height of the keyboard, as it was only covering the intended area partially. So instead of that part you can enter an IntCalcic
Use UIKeyboardFrameEndUserInfoKey to get correct height, and on iPad there are different keyboards heights (w or w/o hardware keyboard) - hardcoding the height will lead to trouble.Arnhem
S
28

Swift 4.2+

@vandana's answer updated to reflect changes to native Notifications in Swift 4.2.

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)

}

@objc func keyboardWillShow(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y == 0 {
            self.view.frame.origin.y -= keyboardSize.height
        }
    }

}

@objc func keyboardWillHide(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y != 0 {
            self.view.frame.origin.y += keyboardSize.height
        }
    }
}

Also, you need to use UIKeyboardFrameEndUserInfoKey to account for safeAreaInset changes introduced with iOS 11.

Superadd answered 20/9, 2018 at 13:35 Comment(5)
It is UIResponder.keyboardWillHideNotification notification nameSunset
I needed the @objc keyword on the functions too.Cisalpine
@RobEllis yes those are required from Swift 4+. Thanks for pointing it out :)Superadd
Do remember to add your observers in viewWillAppear and remove them on viewWillDisappearElevon
@AmeyaVichare https://mcmap.net/q/139153/-objective-c-where-to-remove-observer-for-nsnotificationSuperadd
R
6

set keyboard notification observer in

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardNotification(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
}

and in your function handle it

func keyboardNotification(notification: NSNotification) {
  print("keyboard displayed!!")
}

hope this will help you.

Repay answered 18/1, 2017 at 12:17 Comment(0)
V
5

Swift 4.X / 5

I like the inline, block-based approach which is available for a long time already! You can read more about the parameters of addObserver(...) here.

Some advantages of this approach are:

  • you don't need to use the @objc keyword
  • you write your callback code at the same location where you setup your observer

Important: Call NotificationCenter.default.removeObserver(observer) in the deinit of the object where you set register the observer (often a view controller).

let center = NotificationCenter.default

let keyboardWillShowObserver: NSObjectProtocol = center.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: nil) { (notification) in
    guard let value = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
    let height = value.cgRectValue.height

    // use the height of the keyboard to layout your UI so the prt currently in
    // foxus remains visible
}

let keyboardWillHideObserver: NSObjectProtocol = center.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: nil) { (notification) in

    // restore the layout of your UI before the keyboard has been shown
}
Viviyan answered 23/4, 2019 at 8:39 Comment(0)
C
3

Updated for swift:

// MARK:- Kyeboard hide/show methods

func keyboardWasShown(_ notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y == 0{
            self.view.frame.origin.y -= keyboardSize.height
        }
    }
}

func keyboardWillBeHidden(_ notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y != 0{
            self.view.frame.origin.y += keyboardSize.height
        }
    }
}

func registerForKeyboardNotifications(){
    //Adding notifies on keyboard appearing
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func deregisterFromKeyboardNotifications(){
    //Removing notifies on keyboard appearing
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func textFieldDidBeginEditing(_ textField: UITextField) {
    if textField == mEnterPasswordTextField || textField == mEnterConfirmPassword  {
            animateViewMoving(up: true, moveValue: 120)
    }
}

func textFieldDidEndEditing(_ textField: UITextField) {
    if textField == mEnterPasswordTextField || textField == mEnterConfirmPassword  {
            animateViewMoving(up: false, moveValue: 120)
    }
}

func animateViewMoving (up:Bool, moveValue :CGFloat){
    let movementDuration:TimeInterval = 0.3
    let movement:CGFloat = ( up ? -moveValue : moveValue)
    UIView.beginAnimations( "animateView", context: nil)
    UIView.setAnimationBeginsFromCurrentState(true)
    UIView.setAnimationDuration(movementDuration )
    self.view.frame = self.view.frame.offsetBy(dx: 0,  dy: movement)
    UIView.commitAnimations()
}

// In viewDidLoad()

self.registerForKeyboardNotifications()
self.deregisterFromKeyboardNotifications()
Connection answered 17/4, 2018 at 5:29 Comment(0)
B
2

KeyBoard Will Show And Hide With TxtField In Swift 4

class ViewController: UIViewController {


@IBOutlet weak var commentsTxt: UITextField!
@IBOutlet weak var keyboardBottom: NSLayoutConstraint!

override func viewWillAppear(_ animated: Bool) {
    IQKeyboardManager.shared.enable = false
    NotificationCenter.default.addObserver(
        self,
        selector: #selector(keyboardWillShow),
        name: UIResponder.keyboardWillShowNotification,
        object: nil
    )
    NotificationCenter.default.addObserver(
        self,
        selector: #selector(keyboarddidHide),
        name: UIResponder.keyboardWillHideNotification,
        object: nil
    )
}

@objc func keyboardWillShow(_ notification: Notification) {
    if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
        let keyboardRectangle = keyboardFrame.cgRectValue
        let keyboardHeight = keyboardRectangle.height
        self.keyboardBottom.constant = keyboardHeight - self.bottomLayoutGuide.length
        DispatchQueue.main.asyncAfter(deadline: .now()+0.1, execute: {
            let bottomOffset = CGPoint(x: 0, y: self.scrlView.contentSize.height - self.scrlView.bounds.size.height)
            self.scrlView.setContentOffset(bottomOffset, animated: true)
        })
    }
}
@objc func keyboarddidHide(_ notification: Notification) {
    self.keyboardBottom.constant = 0
    
}

   override func viewWillDisappear(_ animated: Bool) {
    IQKeyboardManager.shared.enable = true
     NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}

}

Blacktail answered 14/10, 2019 at 9:23 Comment(0)
D
1

Try this

 override func viewDidLoad()
    {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
}

 @objc func keyboardWillShow(notification: NSNotification) {
      if(messageCount > 0)
      {
        tableView.scrollToRow(at: IndexPath(item:messageCount - 1, section: 0), at: .bottom, animated: true)
      }
}

@objc func keyboardWillHide(notification: NSNotification) {
    if(messageCount > 0)
    {
        tableView.scrollToRow(at: IndexPath(item:0, section: 0), at: .top, animated: true)
    }
}
Dermatogen answered 30/10, 2018 at 11:17 Comment(0)
T
1

Swift 4.2

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

@objc func didReceiveKeyboardNotificationObserver(_ notification: Notification) {
    let userInfo = notification.userInfo
    let keyboardBounds = (userInfo!["UIKeyboardBoundsUserInfoKey"] as! NSValue).cgRectValue
    let keyboardFrame = (userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).cgRectValue
    let duration = userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! Double
    let curve = userInfo!["UIKeyboardAnimationCurveUserInfoKey"] as! Int
    let frameBegin = (userInfo!["UIKeyboardFrameBeginUserInfoKey"] as! NSValue).cgRectValue
    let centerBegin = (userInfo!["UIKeyboardCenterBeginUserInfoKey"] as! NSValue).cgPointValue
    let center = (userInfo!["UIKeyboardCenterEndUserInfoKey"] as! NSValue).cgPointValue
    let location = userInfo!["UIKeyboardIsLocalUserInfoKey"] as! Int
    println("keyboardBounds: \(keyboardBounds) \nkeyboardFrame: \(keyboardFrame) \nduration: \(duration) \ncurve: \(curve) \nframeBegin:\(frameBegin) \ncenterBegin:\(centerBegin)\ncenter:\(center)\nlocation:\(location)")
    switch notification.name {
    case UIResponder.keyboardWillShowNotification:
    // keyboardWillShowNotification
    case UIResponder.keyboardWillHideNotification:
    // keyboardWillHideNotification
    default:
        break
    }
}
Tecu answered 13/12, 2018 at 18:33 Comment(0)
A
1

Swift 4.2

This version works both on the iPhone 5 and the iPhone X. It works very well if you respect the safe area during your constraints settings.

override func viewDidLoad() {
        super.viewDidLoad()
        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 func keyboardWillShow(notification: NSNotification) {
        if let _ = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            self.view.frame.origin.y = self.navigationController!.navigationBar.frame.size.height + UIApplication.shared.statusBarFrame.size.height
            if self.emailTextField.isFirstResponder {
                self.view.frame.origin.y -= 100
            } else if self.passwordTextField.isFirstResponder {
                self.view.frame.origin.y -= 150
            } else if self.passwordConfirmTextField.isFirstResponder {
                self.view.frame.origin.y -= 200
            }
        }
}

@objc func keyboardWillHide(notification: NSNotification) {
        if self.view.frame.origin.y != 0 {
           self.view.frame.origin.y = self.navigationController!.navigationBar.frame.size.height + UIApplication.shared.statusBarFrame.size.height
        }
}
Amiens answered 18/6, 2019 at 10:8 Comment(0)
A
1

Swift > 4.++

You can use protocol & protocol extension . Let's create KeyboardListener Protocol

protocol KeyboardListener: class {
   func registerKeyboardObserver()
   func keyboardDidUpdate(keyboardHeight: CGFloat)
   func removeObserver()
}

Then create @objc function into UIViewController extension

extension UIViewController {
@objc func adjustForKeyboard(notification: Notification) {
    guard let keyboardValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
    
    let keyboardScreenEndFrame = keyboardValue.cgRectValue
    let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, from: view.window)
    
    if notification.name == UIResponder.keyboardWillHideNotification {
        if let keyboardLister = self as? KeyboardListener {
            keyboardLister.keyboardDidUpdate(keyboardHeight: .zero)
        }
    } else {
        if let keyboardLister = self as? KeyboardListener {
            keyboardLister.keyboardDidUpdate(keyboardHeight: keyboardViewEndFrame.height - view.safeAreaInsets.bottom)
        }
    }
}

}

Then, use Keyboard listener extension for default implementations

extension KeyboardListener where Self: UIViewController {
func registerKeyboardObserver() {
    let notificationCenter = NotificationCenter.default
    notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardWillHideNotification, object: nil)
    notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
}

func removeObserver() {
    NotificationCenter.default.removeObserver(self)
}

}

Finally , we can use it from our ViewController class

extension EditProfileVC: KeyboardListener {
func keyboardDidUpdate(keyboardHeight: CGFloat) {
    //update view when keyboard appear, 
}

}

And call register from viewwillAppear & removeObserver from deinit

 override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    registerKeyboardObserver()
}

deinit {
   removeObserver()
}
Armelda answered 10/6, 2021 at 16:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.