如何滚动到UICollectionView的底部?

时间:2016-07-04 20:42:04

标签: swift firebase uicollectionview firebase-realtime-database

因此,无论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)
    })

1 个答案:

答案 0 :(得分:1)

试试这个

```

DispatchQueue.main.async(execute: { 
                self.collectionView?.reloadData()
                self.scrollToBottom()
            })

``` 在观察闭合内部

这是滚动到底部的函数

```

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)
    }

```