Keyboard Shows and Hide Notification – Swift4

Introduction – Notification when keyboard shows and hide in iPhone
In iOS devices like iPhone and iPad have small screens. we all know that UI in app development requires to have some sort of reference or can say they have constraints or padding form all sides or some other methods like auto layout are there to hold their position and to tell app that where every object has to be placed in screen. And when keyboard in iPhone shows it hides almost half of screen from its own view. So some portion of screen is unaccessible by user while keyboard is shows on screen so to make this problem solving we have to make such notification methods that call our built methods on invoking of keyboard appearing and disappearing.

What role Notification Works in Keyboard Shows and Hides Issue?

Notification whether its a local notification or push notification both are very useful tool in mobile app development. Local or push notification both are great for keeping users informed with continuous track and event invoking functionality plus timely and relevant content whether your app is running in background or in foreground mode. Notifications can display a message, play a distinctive sound, or update a badge on your app icon.By adding observer in notification you can make call a particular function when that event happens

Event used to call in Notification in Keyboard shows and hides

1. UIResponder.keyboardWillShowNotification
2. IResponder.keyboardWillHideNotification

For making Notification in keyboard shows and hides add below code in your UIViewController in which you want to make this Notification calls

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)
}

override func viewDidLoad() {
super.viewDidDisappear()
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self,, name: UIResponder.keyboardWillHideNotification, object: nil)
}

func keyboardWillShow(notification: Notification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] 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?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y != 0 {
self.view.frame.origin.y += keyboardSize.height
}
}
}

Leave a Comment