Tiện ích mở rộng UICollectionView để nhanh chóng thêm ô trống

May 03 2023
Swift code sample Code Trong ví dụ trên, nếu ô thuộc lớp sai, khi gỡ lỗi, lỗi xác nhận sẽ dừng ứng dụng. Tuy nhiên, trong Sản xuất, nếu ô không đúng lớp, một ô trống sẽ được trả về và ứng dụng sẽ tiếp tục chạy.

mẫu mã Swift

Mã số

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)
        }
    }

Trong ví dụ trên, nếu ô thuộc lớp sai, khi gỡ lỗi, lỗi xác nhận sẽ dừng ứng dụng. Tuy nhiên, trong Sản xuất, nếu ô không đúng lớp, một ô trống sẽ được trả về và ứng dụng sẽ tiếp tục chạy.