【发布时间】:2018-04-23 13:49:52
【问题描述】:
因此,当您单击文本字段时,它会起作用,它会根据键盘的大小将其向上移动。很好,但是当我点击离开时,原始框架的底部并没有跟随键盘向下移动。
我的意思是,只有当键盘完全消失时,视图框才会在 0 处恢复到原来的 y。我在下面有一些照片,在第二张照片中,你可以看到键盘向下移动,如丑陋的黑条仍然存在。
有人知道为什么会这样吗?
这是我为使其动画化所做的:
@objc func keyboardWillChange(notification: Notification)
{
guard let keyboardRect = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {
return
}
if notification.name == Notification.Name.UIKeyboardWillShow || notification.name == Notification.Name.UIKeyboardWillChangeFrame
{
view.frame.origin.y = -keyboardRect.height
} else {
view.frame.origin.y = 0
}
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidHide, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
}
viewDidLoad() 内部
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
https://i.imgur.com/P4hIMIW.jpg
https://i.imgur.com/40hXKHk.jpg
编辑:我只是想澄清一下,视图框架确实返回到其原始状态,它只是没有动画,也没有与键盘向下移动同步。它在键盘向下移动后执行此操作,并立即返回 y = 0 而没有动画。当我单击文本字段时,它会随着键盘向上移动而呈现出精美的动画效果。
【问题讨论】:
-
IQKeyboardManager 最适合这个。