我正在使用聊天屏幕,其中我有 InputAccessoryView 用户类型消息和 UICollectionView 其中包含聊天 . 我想在用户在UICollectionView中发送时显示最新的聊天消息 . 问题是当用户类型消息InputAccessoryView出现在键盘上并且UICollectionView落后于键盘时,所以最新消息不可见 . 我想在键盘出现时将UICollectionView移动到键盘高度 .
我正在使用以下代码 .
这将注册键盘隐藏和显示事件的观察者 .
func handleKeyBoard(){
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
var contentInset = self.collectionView?.contentInset
contentInset?.bottom = keyboardSize.height
self.collectionView?.contentInset = contentInset!
if self.messages.count > 0{
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
self.view.layoutIfNeeded()
}, completion: { (completed:Bool) in
let indexPath = IndexPath(item: self.messages.count - 1, section: 0)
self.collectionView?.scrollToItem(at: indexPath, at: .bottom, animated: true)
})
}
}
}
在键盘出现的上述功能中我得到它's height which always comes as 50 I don'知道为什么可能是因为 InputAccessoryView . 获得键盘高度后,我为 InputAccessoryView 添加了50多个高度然后更改 UICollectionViewController 的 contentInset ,并且在动画完成时我滚动到最后一条消息,它将UICollectionViewController滚动到它的最后一条消息 .
但它没有发生 .
对于UICollectionView,这是我的默认 contentInset .
UIEdgeInsets(top: 8, left: 0, bottom: 52, right: 0)
后
var contentInset = self.collectionView?.contentInset
contentInset?.bottom = keyboardSize.height
self.collectionView?.contentInset = contentInset!
contentInset成为了这个 .
UIEdgeInsets(top: 8, left: 0, bottom: 52, right: 0)
一旦键盘隐藏,下面将设置defaul Inset for collectionview
@objc func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
self.collectionView?.contentInset = UIEdgeInsets(top: 8, left: 0, bottom: 52, right: 0)
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
self.view.layoutIfNeeded()
}, completion: { (completed:Bool) in
})
}
}
任何人都可以帮我找到正确的方法来做到这一点 . 这将非常有帮助 . 几乎所有聊天应用都有此功能,当他们键入时,可以在聊天视图中看到新消息 .
谢谢 .