iOS Swift监听键盘通知和获取距离底部间距
2022-04-19 本文已影响0人
Lee坚武
本人亲测有效!绝对可靠!更多交流可以家魏鑫:lixiaowu1129,一起探讨iOS相关技术!
首先在viewDidLoad()方法中:分别添加键盘即将弹出、即将消失和frame修改的通知
//键盘监听
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
2.实现键盘监听事件
/*键盘弹出*/
@objc func keyboardWillShow(_ showNoti:Notification){
KeyboardFrame = (showNoti.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let keyboardY = KeyboardFrame.origin.y
if keyboardY <= self.view.center.y + self.alertView.frame.height/2{
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 15.0, options: .curveLinear, animations: {
if (self.hasTextFields == true && self.firstShow == false){
self.hasTextFields = false;
}
self.alertView.frame.origin.y = keyboardY - self.alertView.frame.height - 15
self.contentView.frame = self.alertView.bounds
}, completion: nil)
}
}
/*键盘隐藏*/
@objc func keyboardWillHide(_ hideNoti:Notification){
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 5.0, options: .curveEaseOut, animations: {
if self.contentViewFrameNormal != nil{
self.alertView.frame = self.contentViewFrameNormal
}
self.alertView.center = self.view.center
self.contentView.frame = self.alertView.bounds
}, completion: nil)
}
3.收起键盘的事件
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
//收起键盘
textField.resignFirstResponder()
return true
}
4.移除通知
deinit {
NotificationCenter.default.removeObserver(self)
print("AntScanCodeViewController deinit")
}