Reputation: 11
How to find index Path for a selected Collection View Cell without using didSelectItemAtIndexPath and prepareForSegue?
I am using this indexPath within AlertViewController. I dont know how to get this indexPath in AlertView Controller.
//Edit Selected Category
let alertController = UIAlertController(title: "Alert", message: "Rename your ", preferredStyle: .alert)
let actionOK = UIAlertAction(title: "OK", style: .default)
alertController.addTextField(configurationHandler: {(textField: UITextField) -> Void in
if let iP: IndexPath = self.collCategory.indexPath(for: CategoryCollectionCell) {
print("IP \(iP)")
}
})
alertController.addAction(actionOK)
self.present(alertController, animated: true, completion: nil)
Upvotes: 0
Views: 6860
Reputation: 661
Here's my solution
private func getCurrentIndex() -> Int {
return Int(collectionView.contentOffset.x / collectionView.frame.width)
}
Upvotes: 1
Reputation: 527
Swift 4-4.2 - Returns index of cell.
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cellIndex = indexPath[1] // try without [1] returns a list.
print(indexPath[1])
chapterIndexDelegate.didTapChapterSelection(chapterIndex: test)
}
Upvotes: 1
Reputation: 1240
Use this:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .bottom)
}
Then u will get path from collectionView.indexPathsForSelectedItems
if let collectionView = self.YourCollectionView,
let indexPath = collectionView.indexPathsForSelectedItems?.first,
let cell = collectionView.cellForItem(at: indexPath) as? YourCell {
}
Upvotes: 4
Reputation: 1701
To select cell without didSelect method then you can use Tap Gesture to detect cell. Check below method to add gesture to cell and detect gesture.
//Add below code to collectionview cell return method
if let gestures = cell. contentView.gestureRecognizers {
gestures.forEach({ (tap) in
if tap .isKind(of: UITapGestureRecognizer.self) == true {
cell.contentView.removeGestureRecognizer(tap)
}
})
}
let tapRec = UITapGestureRecognizer.init(target: self, action: #selector(didTap(sender:)))
cell.contentView.isUserInteractionEnabled = true
cell.contentView.addGestureRecognizer(tapRec)
//Create method to detect gesture recognizer
func didTap(sender: UIGestureRecognizer)
{
let cell = sender.view?.superview as! yourCell
}
Hope it will work.
Upvotes: 0
Reputation: 797
Inside your CollectionView delegate call
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
print(" Row : \(indexPath.row)")
return cell
}
Upvotes: -3