Sazzad Hissain Khan
Sazzad Hissain Khan

Reputation: 40136

Keyboard height not working properly in Swift

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

Upvotes: 2

Views: 405

Answers (1)

M Ohamed Zead
M Ohamed Zead

Reputation: 197

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
}

Upvotes: 2

Related Questions