我正在构建一个信使应用程序。
我当前的键盘通知功能如下:
func handleKeyboardNotification(notification: NSNotification) {
if let userInfo = notification.userInfo {
let keyboardFrame = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue()
print(keyboardFrame)
let isKeyboardShowing = notification.name == UIKeyboardWillShowNotification
bottomConstraint?.constant = isKeyboardShowing ? -keyboardFrame!.height : 0
UIView.animateWithDuration(0, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
self.view.layoutIfNeeded()
}, completion: { (completed) in
if isKeyboardShowing {
let indexPath = NSIndexPath(forItem: self.messages!.count - 1, inSection: 0)
self.collectionView?.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Bottom, animated: true)
}
})
}
}
( bottomConstraint.constant 引用消息输入文本字段,该字段位于屏幕底部或键盘框架顶部)
但是,我希望完成参数中的操作与键盘打开时同时发生,而不是在键盘打开后。目前,当我关闭键盘时,它似乎自动布局很好,而不是在我打开它时。
到目前为止,我尝试过很多方法但无济于事。 有什么建议吗?
答案 0 :(得分:1)
如果您希望在完成时写入的代码块与键盘下降同时发生,那么您不应该在完成块中写入它。 您可以在使用duration函数调用animate之前使用dispatch_async,因此它可以同时工作:
func handleKeyboardNotification(notification: NSNotification) {
if let userInfo = notification.userInfo {
let keyboardFrame = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue()
print(keyboardFrame)
let isKeyboardShowing = notification.name == UIKeyboardWillShowNotification
bottomConstraint?.constant = isKeyboardShowing ? -keyboardFrame!.height : 0
DispatchQueue.main.async {
if isKeyboardShowing {
let indexPath = NSIndexPath(forItem: self.messages!.count - 1, inSection: 0)
self.collectionView?.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Bottom, animated: true)
}
UIView.animateWithDuration(0, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: {self.view.layoutIfNeeded()}, completion: nil})
}
}