Reputation: 1557
I previously passed some data from a tableView like this:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if( segue.identifier == "productList_to_detail" ) {
let VC1 = segue.destination as! ShopItemVC
if afData == 1 {
if let indexPath = self.tableView.indexPathForSelectedRow {
let productIdToGet = sCategory[indexPath.row]
VC1.product_id = productIdToGet.product_id
}
}
}
}
as you can see when I tap on a particular Cell it grabs some data from it and pass the data relative to the Cell . Now I want to do the same but with a CollectionView. When I tap on a particular item of the CollectionView I want to grab some value from it and pass it through segue . How can I do that ?
Upvotes: 2
Views: 194
Reputation: 72410
To access the selected cell's data of collectionView
in prepare(for:sender:)
method it depends on how you have created segue in storyboard.
If Segue
is created from UICollectionViewCell
to Destination ViewController
.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if( segue.identifier == "productList_to_detail" ) {
let VC1 = segue.destination as! ShopItemVC
if let cell = sender as? UICollectionViewCell,
let indexPath = self.collectionView.indexPath(for: cell) {
let productIdToGet = sCategory[indexPath.row]
VC1.product_id = productIdToGet.product_id
}
}
}
If Segue
is created from Source ViewController
to Destination ViewController
.
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//Pass indexPath as sender
self.performSegue(withIdentifier: "productList_to_detail", sender: indexPath)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if( segue.identifier == "productList_to_detail" ) {
let VC1 = segue.destination as! ShopItemVC
if let indexPath = sender as? IndexPath {
let productIdToGet = sCategory[indexPath.row]
VC1.product_id = productIdToGet.product_id
}
}
}
Upvotes: 1