dev*_*996 0 database scroll ios uicollectionview swift
为什么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)
}
}
Run Code Online (Sandbox Code Playgroud)
小智 23
我发现这样做的最佳方法是不使用 scrollToItem 而是获取索引的 CGRect ,然后使其可见。
let rect = self.collectionView.layoutAttributesForItem(at: IndexPath(row: 5, section: 0))?.frame
self.collectionView.scrollRectToVisible(rect!, animated: false)
Run Code Online (Sandbox Code Playgroud)
我使用这样的解决方法:
collectionView.isPagingEnabled = false
collectionView.scrollToItem(
at: /* needed IndexPath */,
at: .centeredHorizontally,
animated: true
)
collectionView.isPagingEnabled = true
Run Code Online (Sandbox Code Playgroud)
试试这个代码...
[collectionView setDelegate:self];
[collectionView reloadData];
[collectionView layoutIfNeeded];
[collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
Run Code Online (Sandbox Code Playgroud)
迅捷-4.x
collectionView.delegate = self
collectionView.reloadData()
collectionView.layoutIfNeeded()
collectionView.scrollToItem(at: IndexPath(item: 0, section: 0), at: .top, animated: true)
Run Code Online (Sandbox Code Playgroud)
当滚动方向为水平时,您需要使用left,right或centeredHorizontally。
顶部是垂直方向。
collectionView.scrollToItem(at: index, at: .top, animated: true)
Run Code Online (Sandbox Code Playgroud)
小智 5
我的问题有点奇怪。我的 iPhone 6/7/8 工作正常,但 iPhone X 或 11 无法滚动到我预期的位置。我的原始代码是:
collectionView.reloadData()
collectionView.scrollToItem(at: IndexPath(item: 10, section: 0), at: .top, animated: true)
Run Code Online (Sandbox Code Playgroud)
在我添加 collectionView.layoutIfNeeded() 之后。问题在我的 iPhone X 和 11 上解决。
collectionView.reloadData()
collectionView.layoutIfNeeded()
collectionView.scrollToItem(at: IndexPath(item: 10, section: 0), at: .top, animated: true)
Run Code Online (Sandbox Code Playgroud)
这个答案的灵感来自@ram。他应该得到信任。添加这个答案只是为了强调不同iPhone之间的区别。所以人们可以更快地搜索他们的答案。