3

I've got a collection view with multiple cells created programically. I want to update a variable to a different value when the user taps a specific cell. So eg: Cell 1 is tapped -> var test = "cell1" , cell2 is tapped var test = "cell2". Usually I'd just create an IBAction by dragging from the storyboard but I'm not sure how to do it in this case.

I'm using Swift 3.1

Nolan Ranolin
  • 409
  • 3
  • 16

2 Answers2

1

To add interactivity to UITableViews, UICollectionViews, and other kinds of views which display collections of data, you can't use Storyboard actions, as the content is generated dynamically during runtime, and the Storyboard can only work for static content.

Instead, what you need to do is set your UICollectionView's delegate property to an object that implements the UICollectionViewDelegate protocol. One of the methods defined as part of the protocol is the collectionView(_:didSelectItemAt:) method. This method will get called whenever the user selects (taps) a collection view cell with the IndexPath to that cell as an argument. You can update your variable in that method. Just remember to deselect the cell after handling the tap by using the deselectItem(at:) method on your UICollectionView.

Pedro Castilho
  • 10,174
  • 2
  • 28
  • 39
0

There are UICollectionView delegate that you need to implement. It goes like this

did select item at index path will give index path of the cell that was selected. Using indexpath or any other property of the data source array you are using, you can modify the variable value.

override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    if let cell = collectionView.cellForItemAtIndexPath(indexPath) {
         //check your condition and modify the variable value depending on index path or any other property you are referring to.
    }
}
Mukul More
  • 554
  • 2
  • 5
  • 18
  • 2
    Although your answer is correct, it uses Swift 2 method names. For example, the `collectionView(_:didSelectItemAtIndexPath:)` method has changed to `collectionView(_:didSelectItemAt:)` and the `cellForItemAtIndexPath` method has changed to `cellForItem(at:)` – Pedro Castilho Apr 17 '17 at 17:03
  • @PedroCastilho thanks for adding the Swift 3 code. Nolan, it would be great if you mention the language as well. – Mukul More Apr 17 '17 at 17:05