Andrea Toso Andrea Toso - 4 months ago 40
Swift Question

indexPath.row reload in UICollectionView

I have a

UICollectionViewController
with 3 rows, in the first indexPath (0) I want to add a
UIView
. When I launch the App it works but when I go into another controller and come back, the
UIView
is in the other rows. This is the code:

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let customCell = collectionView.dequeueReusableCellWithReuseIdentifier(customCellId, forIndexPath: indexPath) as! CustomCell
customCell.nameLabel.text = "\(label2.text) \(materie[indexPath.row])"
customCell.setupViews()
if indexPath.row == 0 {
customCell.setupUIView()
customCell.nameLabel.text = ""
}

return customCell
}


When I launch the app the screen is:

launch screen app

When I go into another controller and come back, the screen is:

screen

Answer

The reason that the square blue is repeated in another cell is because the collectionView is reusing the same cell.

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let customCell = ollectionView.dequeueReusableCellWithReuseIdentifier(customCellId, forIndexPath: indexPath) as! CustomCell

    // HERE YOU HAVE TO RESET THE CELL TO DEFAULT VALUES
    // LIKE REMOVING THE BLUE SQUARE VIEW
    customCell.view2.removeFromSuperview()

    if indexPath.row == 0 {
        customCell.setupUIView()
        customCell.nameLabel.text = ""
    } else {   
        customCell.nameLabel.text = "\(label2.text) \(materie[indexPath.row])"
        customCell.setupViews()
    }

    return customCell
}
Comments