Search code examples
swiftcollectionview

CollectionView cells Confused


I am busy with a speech app with a soundboard when you tap on a CollectionView Cell then iPhone will speak the text. I have a little bug in my app and I don't know what the reason is.

I have built a CollectionView with images as backgroundViews. It works but when I go to an other view ,for example to the Paint view, and I will go back then the cells will confuse.

Can anybody tell me what goes wrong and how I solve it?

Thanks!

enter image description here

This is my code:

 override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    loadData()

    let itemSize = UIScreen.main.bounds.width/2 - 5
    let itemHeight = itemSize / 2
    let layout = UICollectionViewFlowLayout()
    layout.sectionInset = UIEdgeInsets.init(top: 3, left: 3, bottom: 3, right: 3)
    layout.itemSize = CGSize(width: itemSize, height: itemHeight)

    layout.minimumInteritemSpacing = 3
    layout.minimumLineSpacing = 3

    soundboard.collectionViewLayout = layout

    navigationItem.rightBarButtonItem = editButtonItem

    if(traitCollection.forceTouchCapability == .available){
        registerForPreviewing(with: self as UIViewControllerPreviewingDelegate, sourceView: collectionView)
    }
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)

    loadData()
}

func loadData() {
    let soundRequest:NSFetchRequest<Soundboard> = Soundboard.fetchRequest()

    do {
        soundBoardData = try managedObjectContext.fetch(soundRequest)
        self.soundboard.reloadData()
    } catch {
        print("Error")
    }
}


// MARK: - Collection View
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return soundBoardData.count
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> soundboardCellVC {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! soundboardCellVC

    let soundItem = soundBoardData[indexPath.row]


    if let getCellPhoto = soundItem.photo as Data? {

        cell.title.text = "";

        let cellPhoto = UIImage(data: getCellPhoto)


        let cellPhotoFrame = UIImageView(image:cellPhoto)


        cellPhotoFrame.frame = CGRect(x: 0, y: 0, width: cell.frame.width, height: cell.frame.height)
        cellPhotoFrame.contentMode = UIView.ContentMode.scaleAspectFill

        cell.backgroundView = UIView()
        cell.backgroundView!.addSubview(cellPhotoFrame)
    }
    else
    {
        cell.title.text = soundItem.title;

        cell.backgroundColor = UIColor(red: CGFloat(soundItem.colorRed), green: CGFloat(soundItem.colorGreen), blue: CGFloat(soundItem.colorBlue), alpha: 1)

        let fontAwesomeIcon = FAType(rawValue: Helper.FANames.index(of: soundItem.icon!)!)

        cell.icon.setFAIconWithName(icon: fontAwesomeIcon!, textColor: UIColor.white)
    }

    cell.layer.cornerRadius = 10
    cell.layer.masksToBounds = true

    cell.delegate = self as SoundboardCellDelegate

    return cell
}

Solution

  • A good practice when working with cells is to clear any properties that you don't want to persist when the cell gets reused.

    https://developer.apple.com/documentation/uikit/uicollectionreusableview/1620141-prepareforreuse

    For example in your cells class you can do:

    override func prepareForReuse() {
        super.prepareForReuse()
        self.title.text = nil
    }
    

    This keeps your cellForItem method cleaner, and you know for sure that the above actions will have been carried out before you reuse it.