UICollectionView程序化滚动

问题描述 投票:0回答:1

我想要做的是在我的内容加载后立即将我的CollectionView滚动到最底部。

这是我的代码;

func bindSocket(){
    APISocket.shared.socket.on("send conversation") { (data, ack) in
        let dataFromString = String(describing: data[0]).data(using: .utf8)
        do {
            let modeledMessage = try JSONDecoder().decode([Message].self, from: dataFromString!)
            self.messages = modeledMessage
            DispatchQueue.main.async {
                self.collectionView.reloadData()
                let indexPath = IndexPath(item: self.messages.count - 1, section: 0)
                self.collectionView.scrollToItem(at: indexPath, at: .bottom, animated: false)
            }
        } catch  {
            //show status bar notification when socket error occurs
        } 
    }
}

但它完全不起作用。

顺便说一句,我使用InputAccessoryView作为粘性数据输入栏,如在iMessage和使用collectionView.keyboardDismissMode = .interactive

谢谢,

ios iphone swift uikit
1个回答
0
投票

我想你可能会在你的collectionView之前调用func获取可见单元格或调用reload collection视图然后立即滚动项目,此时滚动到indexPath将没有意义,因为集合视图的内容大小尚未更新。

scrollToItem(在:在:动画:)

滚动集合视图内容,直到指定的项目可见。

试试这个:

self.collectionView.reloadData()
let indexPath = IndexPath(item: self.messages.count - 1, section: 0)
let itemAttributes = self.collectionView.layoutAttributesForItem(at: indexPath)
self.collectionView.scrollRectToVisible(itemAttributes!.frame, animated: true)
© www.soinside.com 2019 - 2024. All rights reserved.