我创建了一个新项目,它只包含一个 UICollectionView
和一个 UIButton
。 collectionView 包含 30 个单元格,全部位于第 0 部分。并且并非所有单元格都可以同时可见。
按钮的 Action 在这里:
@IBAction func button(sender: UIButton) {
collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 29, inSection: 0), atScrollPosition: .CenteredVertically, animated: false)
print(collectionView.indexPathsForVisibleItems())
}
在模拟器中,当触摸按钮内部时,collectionView 会滚动到最后一个单元格。然后,将可见单元格的 indexPaths 打印到控制台。
问题是在触摸按钮后我找不到最后一个单元格的 indexPath 被打印。为什么?
最佳答案
在我看来,即使你在没有动画的情况下调用“scrollToItemAtIndexPath”,但是,当它被执行时,最后一个可见单元格到最后一个单元格之间的单元格将被创建和渲染。此外, Collection View 将在此期间布局 subview 。这样您的“打印”调用就会在之前执行。我打印出“cellForItemAtIndexPath”来证明这一点。还有一件事是,如果您在 0.5 秒后调用“打印”延迟,它将打印最后一个单元格。
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.collectionView.delegate = self
self.collectionView.dataSource = self
self.collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellIdentifier")
}
@IBOutlet weak var collectionView: UICollectionView!
@IBAction func didButtonPress(sender: AnyObject) {
let section = 0
let lastItemIndex = self.collectionView.numberOfItemsInSection(section) - 1
let indexPath:NSIndexPath = NSIndexPath.init(forItem: lastItemIndex, inSection: section)
self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Bottom, animated: false)
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
print(self.collectionView.indexPathsForVisibleItems())
}
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSizeMake(80, 80)
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 60
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cellIdentifier", forIndexPath: indexPath)
cell.backgroundColor = UIColor.redColor()
print(indexPath)
return cell
}
希望对您有所帮助。
关于ios - UICollectionView.scrollToItemAtIndexPath 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36966290/