如何自动选择进入视图的图像?
我知道我可以在默认情况下选择集合视图中的第一个项目,但是如何对进入视图的每个项目进行操作?更详细地解释它:我有一个图像视图,具体取决于CollectionView的选择。我想做的是,用户不必选择CollectionViewCell即可获得依赖图像视图。我希望用户仅通过收集视图滑动,并且选择了出现的图像,并且根据ImageView中显示了概述。我认为,主要的问题是,我只需要一次选择一个。
您可以尝试启用多个选择:
collectionView.allowsMultipleSelection = true
然后在循环中选择要选择的项目:
collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .top)
编辑
您可以使用UICollectionViewDelegate
的willDisplay
委托方法在显示单元格时进行选择:
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)
}
据我了解您的问题,请尝试选择cellForItemAt indexPath
中的项目。因此,一旦加载单元格(显示(,您就可以选择它。
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
[...]
collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .top)
[...]
}
也如其他答案所述:collectionView.allowsMultipleSelection = true
我认为您应该使用collectionView:willDisplayCell:forItemAtIndexPath:
而不是cellForItemAtIndexPath:
(上面提到(调用selectItem(at:animated:scrollPosition:)
,这将确保单元格实际上要显示。