所以我当前的代码根本不会滚动列表,不管 messageCount 返回的数字是多少。它位于 viewDidLoad() 中,数据由 Firebase 填充。这是什么原因造成的?
当前代码:
self.messages.removeAll()
collectionView?.reloadData()
refHandle = self.ref.child("messages").observeEventType(.ChildAdded, withBlock: { (snapshot) -> Void in
self.messages.append(snapshot)
self.collectionView?.insertItemsAtIndexPaths([NSIndexPath(forItem: self.messages.count - 1, inSection: 0)])
})
refHandle = ref.child("messages").observeEventType(FIRDataEventType.Value, withBlock: { (snapshot) in
let messageCount = Int(snapshot.childrenCount)
print(messageCount) //temp
self.collectionView?.scrollToItemAtIndexPath(NSIndexPath(forItem: messageCount - 1, inSection: 0), atScrollPosition: .Bottom, animated: true)
})
最佳答案
试试这个
```
DispatchQueue.main.async(execute: {
self.collectionView?.reloadData()
self.scrollToBottom()
})
``` 在 observe 闭包内
这是滚动到底部的功能
```
func scrollToBottom() {
let section = (collectionView?.numberOfSections)! - 1
let lastItemIndex = IndexPath(item: self.messages.count - 1, section: section)
self.collectionView?.scrollToItem(at: lastItemIndex, at: .bottom, animated: true)
}
```
关于swift - 如何滚动到 UICollectionView 的底部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38191975/