键盘高度在 Swift 中无法正常工作
Keyboard height not working properly in Swift
我正在使用以下代码在键盘显示和隐藏时调整当前视图。当键盘显示代码有效时,但当它隐藏视图时,视图在底部滑动移动,并在顶部保持黑色 space。 如何解决?
@objc func keyboardWillAppear(notification: Notification){
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
self.view.frame.origin.y = -keyboardHeight/2
}
}
@objc func keyboardWillHide(notification: Notification){
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
self.view.frame.origin.y = +keyboardHeight/2
}
}
您可以变换视图而不是分配给原点
@objc func keyboardWillAppear(notification: Notification){
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
self.view.transform = CGAffineTransform(translationX: 0, y: -keyboardHeight/2)
}
}
@objc func keyboardWillHide(notification: Notification){
self.view.transform = .identity
}
我正在使用以下代码在键盘显示和隐藏时调整当前视图。当键盘显示代码有效时,但当它隐藏视图时,视图在底部滑动移动,并在顶部保持黑色 space。 如何解决?
@objc func keyboardWillAppear(notification: Notification){
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
self.view.frame.origin.y = -keyboardHeight/2
}
}
@objc func keyboardWillHide(notification: Notification){
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
self.view.frame.origin.y = +keyboardHeight/2
}
}
您可以变换视图而不是分配给原点
@objc func keyboardWillAppear(notification: Notification){
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
self.view.transform = CGAffineTransform(translationX: 0, y: -keyboardHeight/2)
}
}
@objc func keyboardWillHide(notification: Notification){
self.view.transform = .identity
}