我正在创建一个聊天界面,就像WhatsApp一样,我创建了一个“scrollToBottom”按钮,当用户以一定距离滚动集合时会出现该按钮。当键盘出现时,此按钮完全跟随键盘框架,当消失时,唯一的问题是当键盘被交互式解除时,我无法使该按钮跟随键盘框架。只有在隐藏键盘后,系统才会发送通知并且按钮会更改其常量。
我已尝试过所有键盘通知,但没有人帮我解决这个问题。我需要一些及时的东西,使按钮跟随键盘没有任何延迟。即使UIKeyboardWillChangeFrameNotification
也没有为我工作。
NSNotificationCenter.defaultCenter().addObserver(self,
selector:#selector(self.keyboardWillShow(_:)),
name:UIKeyboardWillShowNotification,
object:nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector:#selector(self.keyboardWillHide(_:)),
name:UIKeyboardWillHideNotification,
object:nil)
private func configureConstantViewNewMessages(notification: NSNotification){
if let userInfo = notification.userInfo {
let animationDuration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
let keyboardEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
let convertedKeyboardEndFrame = view.convertRect(keyboardEndFrame, fromView: view.window)
let rawAnimationCurve = (notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).unsignedIntValue << 16
let animationCurve = UIViewAnimationOptions(rawValue: UInt(rawAnimationCurve))
self.kNewMessages.constant = CGRectGetMaxY(view.bounds) - CGRectGetMinY(convertedKeyboardEndFrame) + 10
UIView.animateWithDuration(animationDuration, delay: 0.0, options: [.BeginFromCurrentState, animationCurve], animations: {
self.view.layoutIfNeeded()
}, completion: nil)
}
}
使用上面的代码,我调用方法configureConstantViewNewMessages
来设置按钮常量(kNewMessages)的动画,并且可以根据键盘高度更改其位置。
感谢您对英语错误的支持和抱歉。
答案 0 :(得分:1)
请使用以下代码可能适合您。
override func viewWillAppear(animated: Bool) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
}
func keyboardWillShow(notification:NSNotification) {
let userInfo:NSDictionary = notification.userInfo!
let keyboardFrame:NSValue = userInfo.valueForKey(UIKeyboardFrameEndUserInfoKey) as! NSValue
let keyboardRectangle = keyboardFrame.CGRectValue()
let keyboardHeight = keyboardRectangle.height
print(keyboardHeight)
}
答案 1 :(得分:1)