Hızlı bir şekilde boş bir hücre eklemek için bir UICollectionView uzantısı

May 03 2023
Swift kodu örneği Kodu Yukarıdaki örnekte, hücre yanlış sınıftaysa, hata ayıklama sırasında bir doğrulama hatası uygulamayı durduracaktır. Ancak Üretimde hücre yanlış sınıftaysa boş bir hücre döndürülür ve uygulama çalışmaya devam eder.

Swift kodu örneği

kod

final class FallbackBlankCollectionViewCell: UICollectionViewCell {}

extension UICollectionView {
    func blankCell(forIndexPath: IndexPath) -> UICollectionViewCell {
        register(FallbackBlankCollectionViewCell.self, forCellWithReuseIdentifier: "FallbackBlankCollectionViewCell")
        return dequeueReusableCell(withReuseIdentifier: "FallbackBlankCollectionViewCell", for: forIndexPath)
    }
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LobbyCell", for: indexPath) as? LobbyCell {
            return cell
        } else {
            assertionFailure()
            return collectionView.blankCell(forIndexPath: indexPath)
        }
    }

Yukarıdaki örnekte, hücre yanlış sınıftaysa hata ayıklama sırasında bir onaylama hatası uygulamayı durduracaktır. Ancak Üretimde hücre yanlış sınıftaysa boş bir hücre döndürülür ve uygulama çalışmaya devam eder.