首页 > 解决方案 > scrollToItem 在我的 CollectionView 中不起作用?

问题描述

为什么 scrollToItem 在我的 CollectionView 中不起作用?我想在 scrollToItem 上工作EnabledID。那么什么是问题以及如何解决呢?

代码:

var dataArray = NSMutableArray() // dataArray is has a data from Database
var EnabledID = Int()

EnabledID = UserDefaults.standard.integer(forKey: "EnabledID")
    
if EnabledID == 0 {
        
    EnabledID = 1
    UserDefaults.standard.set(1, forKey: "EnabledID")
        
} else {
    if EnabledID < dataArray.count {
        let index = NSIndexPath(item: EnabledID, section: 0)
        self.myCollectionView.scrollToItem(at: index as IndexPath, at: .centeredVertically, animated: true)
    }
}
    

标签: iosswiftuicollectionviewuiscrollviewuserdefaults

解决方案


试试这个代码...

[collectionView setDelegate:self];
[collectionView reloadData];
[collectionView layoutIfNeeded];
[collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];

斯威夫特 - 4.x

collectionView.delegate = self
collectionView.reloadData()
collectionView.layoutIfNeeded()
collectionView.scrollToItem(at: IndexPath(item: 0, section: 0), at: .top, animated: true)

当滚动方向为水平时,您需要使用leftrightcenteredHorizo​​ntally

顶部是垂直方向。

collectionView.scrollToItem(at: index, at: .top, animated: true)

推荐阅读