I have a simple ViewController
The problem is the code print("HEIGHT (keyboardSize.height)") prints Height = 69
Why ? I have set input view frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 30) So I expect the heigh would be 30 but it is not.
The problem appears only on iPhoneX.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textField.inputView = SoftView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
addCustomKeyboardNotification()
}
private func addCustomKeyboardNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(customKeyboardWillAppearNotification), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(customKeyboardWillHideNotification), name: UIResponder.keyboardWillHideNotification, object: nil)
}
private func removeCustomKeyboardNotification() {
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc
private func customKeyboardWillAppearNotification(notification: Notification) {
guard let keyboardSize = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect,
let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double else {
return
}
print("HEIGHT \(keyboardSize.height)")
UIView.animate(withDuration: duration) {
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
}
}
@objc
private func customKeyboardWillHideNotification(notification: Notification) {
guard let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double else {
return
}
UIView.animate(withDuration: duration) {
self.view.layoutIfNeeded()
}
}
}
class SoftView: UIView {
init() {
super.init(frame: .zero)
self.refresh()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func refresh() {
self.backgroundColor = .green
self.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 30)
self.layoutIfNeeded()
}
}