如何滚动到UICollectionView的底部?

时间:2022-06-03 07:32:33

So my current code will not scroll the list at all, regardless of the number returned by messageCount. This is located in viewDidLoad() and the data is populated by Firebase. What it causing this?

因此,无论messageCount返回的数字是什么,我的当前代码都不会滚动列表。它位于viewDidLoad()中,数据由Firebase填充。它导致了什么?

Current Code:

    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 个解决方案

#1


1  

try this

```

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

``` inside the observe closure

```在观察闭合内部

and this is the scroll to bottom func

这是滚动到底部的功能

```

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

```

#1


1  

try this

```

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

``` inside the observe closure

```在观察闭合内部

and this is the scroll to bottom func

这是滚动到底部的功能

```

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

```