UICollectionview scrollToItemAtIndexPath, not loading visible cells until animation complete

妖精的绣舞 提交于 2019-12-05 23:29:38

Swift 3.0 OR up

add "view.layoutIfNeeded()" before implementing scrollToItem method, Ideally in viewWillAppear

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
view.layoutIfNeeded()
  colView.scrollToItem(at: IndexPath(item: 4, section: 0), at: .centeredHorizontally, animated: true)}

I use dispatch_async to update the UI and it works.

let numberOfSections = self.collectionView.numberOfSections()
let numberOfRows = self.collectionView.numberOfItemsInSection(numberOfSections-1)

    if numberOfRows > 0 {
        dispatch_async(dispatch_get_main_queue(), {
            let indexPath = NSIndexPath(forRow: numberOfRows-1, inSection: (numberOfSections-1))
            self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Bottom, animated: true)
        })
    }

The only answer I have found, is to add a few seconds to the animation. That way the cells are loaded when the scroll arrives

The best solution I found was to use DispatchQueue.

Swift 4.2:

 override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    if let index = items.firstIndex(of: preSelectedItem) {
        DispatchQueue.main.async {
            self.collectionView.scrollToItem(at: IndexPath(item: index, section: 0), at: .top, animated: false)
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!