I am using below code to adjust current view when keyboard is showing and hiding. When keyboard is showing the code works, but when its hiding the view moving slidely bottom keeping a black space at the top. How to resolve it?
@objc func keyboardWillAppear(notification: Notification){
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
self.view.frame.origin.y = -keyboardHeight/2
}
}
@objc func keyboardWillHide(notification: Notification){
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
self.view.frame.origin.y = +keyboardHeight/2
}
}
You can transform the view instead of assigning to origin
@objc func keyboardWillAppear(notification: Notification){
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
self.view.transform = CGAffineTransform(translationX: 0, y: -keyboardHeight/2)
}
}
@objc func keyboardWillHide(notification: Notification){
self.view.transform = .identity
}