How to automatically select the item, which is visible, in collection view? Swift 4

How can I achieve that the images which comes into view is automatically selected?

I know that I can have the first item in the collection view selected by default, but how to do it with every item that comes into view? To explain it in more detail: I have an imageview depending on the selection of the collectionView. What I want to do is, that the user don't have to select the collectionViewcell to get the depending imageview. I want the user to just swipe through the collection view and the image that comes up is selected and an overview shown in the depending imageview. The main problem is in my opinion, that I need to Ave just one selected at a time.

Upvotes: 2

Views: 2617

Answers (3)

congsun
congsun

Reputation: 144

I think you should use collectionView:willDisplayCell:forItemAtIndexPath: rather than the cellForItemAtIndexPath: (mentioned above) to call the selectItem(at:animated:scrollPosition:), this will ensure the cell is actually about to show.

Upvotes: 1

Milan Nosáľ
Milan Nosáľ

Reputation: 19737

You can try to enable multiple selection:

collectionView.allowsMultipleSelection = true

And then in a loop select items that you want to have selected:

collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .top)

EDIT

You can use willDisplay delegate method of the UICollectionViewDelegate to do the selection when the cell is being displayed:

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)
}

Upvotes: 3

Tung Fam
Tung Fam

Reputation: 8147

As far as I understood your question try this selecting an item in the cellForItemAt indexPath. So as soon as the cell is loaded (shown) you select it.

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    [...]

    collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .top)

    [...]
}

Also as mentioned in other answer: collectionView.allowsMultipleSelection = true

Upvotes: 1

Related Questions