Вот код, который я лично использую.Это NSLayoutContraint.В раскадровке вы можете выбрать Bottom Layout Guide и изменить его класс на KeyboardNSLayoutConstraint.
import UIKit
public class KeyboardNSLayoutConstraint: NSLayoutConstraint {
private var offset : CGFloat = 0
private var keyboardVisibleHeight : CGFloat = 0
override public func awakeFromNib() {
super.awakeFromNib()
offset = constant
NotificationCenter.default.addObserver(self, selector: #selector(KeyboardLayoutConstraint.keyboardWillShowNotification(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(KeyboardLayoutConstraint.keyboardWillHideNotification(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc func keyboardWillShowNotification(_ notification: Notification) {
if let userInfo = notification.userInfo {
if let frameValue = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let frame = frameValue.cgRectValue
keyboardVisibleHeight = frame.size.height
//If device is an iPhone X, it changes the layout constraint to accomodate for the bottom bar
if (UIDevice.current.modelName == "iPhone10,3") || (UIDevice.current.modelName == "iPhone10,6") {
keyboardVisibleHeight = keyboardVisibleHeight - 34
}
}
self.updateConstant()
switch (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber, userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber) {
case let (.some(duration), .some(curve)):
let options = UIViewAnimationOptions(rawValue: curve.uintValue)
UIView.animate(withDuration: TimeInterval(duration.doubleValue), delay: 0, options: options, animations: { UIApplication.shared.keyWindow?.layoutIfNeeded()
return
}, completion: { finished in })
default:
break
}
}
}
@objc func keyboardWillHideNotification(_ notification: NSNotification) {
keyboardVisibleHeight = 0
self.updateConstant()
if let userInfo = notification.userInfo {
switch (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber, userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber) {
case let (.some(duration), .some(curve)):
let options = UIViewAnimationOptions(rawValue: curve.uintValue)
UIView.animate(withDuration: TimeInterval(duration.doubleValue), delay: 0, options: options, animations: {
UIApplication.shared.keyWindow?.layoutIfNeeded()
return
}, completion: { finished in })
default: break
}
}
}
func updateConstant() {
self.constant = offset + keyboardVisibleHeight
}
}