How to get indexPath
of collectionViewCell
on Button click and Button is in Out sided from collectionviewCell
. I am trying with sender
and Superview
. But it is not working.
@IBAction func btnCancel(_ sender: Any) {
if let cell = (sender as AnyObject).superview??.superview?.superview?.superview?.superview?.superview as? ImageShowinPopUpCell {
let indexPath = collectionview.indexPath(for: cell)
deleteDublicateImage(id: isNilValue(assignValue: dbImageDataModel![(indexPath?.row)!].id))
collectionview.reloadData()
if dbImageDataModel.count == 0
{
dismiss(animated: true, completion: nil)
}
}
}
import UIKit
class ViewController: UIViewController ,UICollectionViewDelegate&UICollectionViewDataSource&UICollectionViewDelegateFlowLayout{
@IBOutlet weak var collectionView: UICollectionView!
var currentIndexPath:IndexPath!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
collectionView.delegate = self
collectionView.dataSource = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
cell.backgroundColor = indexPath.row % 2 == 1 ? .blue : .red
return cell
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
currentIndexPath = indexPath
}
@IBAction func indexPathAction(_ sender: UIButton) {
print("Current IndexPath",currentIndexPath)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return collectionView.bounds.size
}
}