Search code examples
iosswiftuicollectionviewindexpath

find middle cell in a collection view and change its content


My goal is to have full text in a middle cell and truncated text in other cells, but with change of middle cell this style should not change (means middle one full text and others truncated).

Presets: Infinite scroll in horizontally scrolling collection view with label in the cells.

I have 3 cells and they should look like this [ 1D ]---[ 1 Day ]---[ 1D ]


Solution

  • You can do something like this to find the middle cell:

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CELL_ID", for: indexPath)
    
        let center = self.view.convert(collectionView.center, to: collectionView)
        let index = collectionView.indexPathForItem(at: center)
    
        if (indexPath == index) {
            // truncated text
        } else {
            // don't truncated text
        }
    
        return cell
    }