核心: 通过系统的通知 获取 键盘的高度尺寸, 再移动相应的视图;
得到键盘的 Frame 信息:
let eFrame = notification?.userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect
企业微信截图_987c6631-4e19-4b09-a69a-ae2693295047.png
- 解析出键盘的高度:
import Foundation
import UIKit
// 全局用: 静态工具
struct TyeTool{
static func yeGetKeyboardFrame(notification: Notification?) -> CGRect
{ // 得到键盘的信息:Frame
guard let eUserInfo = notification?.userInfo, let eFrame = eUserInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect
else { return CGRect(x: 0, y: 0, width: 0, height: 0)}
return eFrame
}
}
- 监听键盘的弹窗与隐藏 (通知):
//--- 系统通知监听 键盘显示和隐藏 : 解决 键盘遮挡输入框的问题:
func yeAddNotificationForkeyboard(){
NotificationCenter.default.addObserver(self,
selector: #selector(yeKeyboardWillShow(_:)),
name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(yeKeyboardWillHide(_:)),
name: UIResponder.keyboardWillHideNotification, object: nil)
}
- 根据得到的 键盘高度 移动相应的视图 :
@objc func yeKeyboardWillShow(_ notification: Notification?)
{ // 键盘 弹出;
print("---键盘 弹出--")
// 1. 得到 键盘的高度:
let eKeyboardFrame = TyeTool.yeGetKeyboardFrame(notification: notification)
let eKeyboardH = eKeyboardFrame.height
UIView.animate(withDuration: 0.3, delay: 0.0, animations: { [self] in
self.eUITextField.frame.origin.y -= eKeyboardH
}) { eBool in
print("---动画完成--")
}
}
@objc func yeKeyboardWillHide(_ notification: Notification?)
{ // 键盘 隐藏;
print("---键盘 隐藏--")
let eKeyboardFrame = TyeTool.yeGetKeyboardFrame(notification: notification)
let eKeyboardH = eKeyboardFrame.height
UIView.animate(withDuration: 0.3, delay: 0.0, animations: { [self] in
self.eUITextField.frame.origin.y += eKeyboardH
}) { eBool in
print("---动画完成--")
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}