Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the indexPath of the current cell

I have currently trying to create a way to delete an item in a collection view at the indexPath of 1 back. So far i have used some help to create a function with scrollview did scroll to create a way to count which image the user is on by the current image method. I now need a way to count which cell the user is on. Here is my code>

 var currentImage = 0
   func scrollViewDidScroll(_ scrollView: UIScrollView) {
let x = floor(myCollectionView.contentOffset.x / view.frame.width)
if Int(x) != currentImage {
    currentImage = Int(x)
    //print(currentImage)
}
if currentImage > 0 {
                for collectionCell in myCollectionView.visibleCells  as [UICollectionViewCell]    {
        let indexPath = myCollectionView.indexPath(for: collectionCell as UICollectionViewCell)!
       let indexPathOfLastItem = (indexPath?.item)! - 1
            let indexPathOfItemToDelete = IndexPath(item: (indexPathOfLastItem), section: 0)
            imageArray.remove(at: 0)
            myCollectionView.deleteItems(at: [indexPathOfItemToDelete])
            currentImage =  1
like image 545
Nivix Avatar asked Mar 28 '17 00:03

Nivix


People also ask

What is IndexPath in Tableview Swift?

Swift version: 5.6. Index paths describe an item's position inside a table view or collection view, storing both its section and its position inside that section.

How do I create an IndexPath in Objective C?

To create an IndexPath in objective C we can use. NSIndexPath *myIP = [NSIndexPath indexPathForRow: 5 inSection: 2] ; To create an IndexPath in Swift we can use.


1 Answers

Based more on the comments than your actual question, what you seem to want is to get the first visible cell's index path so you can use that path to delete the cell.

let visibleCells = myCollectionView.visibleCells
if let firstCell = visibleCells.first() {
    if let indexPath = myCollectionView.indexPath(for: collectionCell as UICollectionViewCell) {
        // use indexPath to delete the cell
    }
}

None of this should be used or done in the scrollViewDidScroll delegate method.

like image 119
rmaddy Avatar answered Oct 12 '22 02:10

rmaddy