如何实现自动选择进入视野的图像?
我知道我可以在默认情况下选择集合视图中的第一个项目,但是如何对每个进入视图的项目执行此操作? 为了更详细地解释它:我有一个imageview取决于collectionView的选择。我想要做的是,用户不必选择collectionViewcell来获取依赖的imageview。我希望用户只需在集合视图中滑动,就可以选择出现的图像,并在依赖图像视图中显示概述。 在我看来,主要问题是我需要一次只选择一个。
答案 0 :(得分:2)
您可以尝试启用多项选择:
collectionView.allowsMultipleSelection = true
然后在循环中选择您想要选择的项目:
collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .top)
修改强>
您可以使用willDisplay
UICollectionViewDelegate
委托方法在显示单元格时进行选择:
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
// this is called before the cell is displayed, check if this is the cell to be selected, and if yes, select it:
collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .top)
}
答案 1 :(得分:1)
据我了解您的问题,请尝试选择cellForItemAt indexPath
中的项目。因此,只要加载(显示)单元格,就选择它。
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
[...]
collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .top)
[...]
}
另外在其他答案中提及:collectionView.allowsMultipleSelection = true
答案 2 :(得分:1)
我认为您应该使用collectionView:willDisplayCell:forItemAtIndexPath:
而不是cellForItemAtIndexPath:
(如上所述)来调用selectItem(at:animated:scrollPosition:)
,这样可以确保单元格实际显示。