我有一个很小的问题 - 我们可以使用通知计算键盘高度。所有股份溢出中的答案都是使用NSNOTIFIENT,但是是否有更简单的方法来计算它?
以下是代码:
NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil
@objc func keyboardWillShow(notification: ) {
if let userInfo = notification.userInfo {
if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
let kbHeight = keyboardSize.height
}
}
}
代码在TextFieldDidBeginediting中使用键盘高度:
var kbHeight: CGFloat?
@objc func keyboardWillShow(notification: NSNotification) {
if let userInfo = notification.userInfo {
if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
kbHeight = keyboardSize.height
}
}
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField.frame.maxY > self.kbHeight!
{
self.scrollView.setContentOffset(CGPoint.init(x: 0, y: textField.frame.maxY - (self.kbHeight! + 2.0)), animated: true)
}
else{
return
}
print(textField.frame.maxY)
print(self.view.frame.height * 0.6)
print(textField.frame.maxY - self.view.frame.height * 0.6)
}
func textFieldDidEndEditing(_ textField: UITextField)
{
self.scrollView.setContentOffset(CGPoint.init(x: 0, y: 0), animated: true)
self.view.endEditing(true);
}
实际上我没有任何直接获取键盘高高的想法。但是,当存在键盘时,您可以将键盘高度保存在变量中,并在您想要的地方使用
使用这两个观察者进行键盘并管理键盘Hight
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
必须在dinit方法中删除这些观察者,当时弹出或解散视图控制器。
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
键盘通知的选择方法...
@objc func keyboardWillShow(notification: NSNotification) {
var keyBoardHeight: CGFloat = 0
if let keyboardFrame: NSValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
keyBoardHeight = keyboardRectangle.height
}
}
@objc func keyboardWillHide(notification: NSNotification) {
}