Nolan Ranolin
Nolan Ranolin

Reputation: 409

Change Variable based on Cell Clicked

I want to set a variable to different string when a certain CollectionView cell is tapped. So cell1 is tapped then var cellTapped = "cell1", cell 2 is tapped then var cellTapped = "cell2" and so on. It was suggested that I

"create a custom cell and hold the value as property and read this value on didSelectCell()"

but I'm not sure how to do this (newbie).

(Swift 3)

Upvotes: 0

Views: 174

Answers (2)

adamfowlerphoto
adamfowlerphoto

Reputation: 2751

Setup your view controller to be the delegate of the UICollectionView. Your view controller should inherit from UICollectionViewDelegate. Then in the viewDidLoad() for the VC set the delegate variable for the UICollectionView to be the ViewController. To catch selection events override the following UICollectionViewDelegate function.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    cellTapped = "cell\(indexPath.row)"
}

Check out https://www.raywenderlich.com/136159/uicollectionview-tutorial-getting-started for more details on working with collection views

Upvotes: 1

toddg
toddg

Reputation: 2906

You need to set UICollectionViewDelegate to your ViewController and then implement didSelectItemAt IndexPath that gets called when a cell is tapped.

Something like this:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    cellTapped = "cell" + String(indexPath.row)
}

You could also have an array of Strings and index into the array based on the indexPath.row:

let cellStringValues = ["cell1", "cell2", "cell3", ... , "celln"]

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    cellTapped = cellStringValues[indexPath.row]
}

Upvotes: 1

Related Questions