implement cell selection
Now, to implement cell selection and print the selected cell go to Collection View Controller and Use the following piece of code
import UIKit
class CollectionViewController: UICollectionViewController {
let dataSource: [String] = ["Aanya", "Akhil" , "Ryan", "Suzie", "Lakshya", "Vivant", "Tejaswi", "Zayn"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSource.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var cell = UICollectionViewCell()
if let contactCell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? CollectionViewCell{
contactCell.configure(with: dataSource[indexPath.row])
cell = contactCell
}
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("Selected contact \(dataSource[indexPath.row])")
}
}
Output:
Thus we can see that the cells are individual data sources that can print the label on them when clicked on.