swift - 如何滚动到 UICollectionView 的底部?

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

最佳答案

试试这个

```

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/

相关文章:

ios - swift SpriteKit : Creating a realistic driving experience 2D

ios - Firebase-Swift : How to add every created user to a friends list when created?

ios - FCM 通知未收到 iOS

ios - UICollectionView 3x 一行

ios - 旋转时是否需要更新 TableView 布局?

ios - 从所有 Swift 文件访问数组

ios - dyld:Xcode 更新后未加载库:@rpath/libswiftCore.dylib

javascript - 将 forEach 与内部事件同步(Firebase 和 Node 6.11.5)

java - 使用适用于 Android 的 Firebase 发送电子邮件验证时未检查的分配警告

ios - 如何在 UICollectionView 中隐藏一个部分