Swift class available switch depending on iOS version for UICollectionViewCell vs UICollectionViewListCell

330 views Asked by At

For iOS13 my cell class is UICollectionViewCell, and in iOS14 i want the same class to be UICollectionViewListCell, which is available only in iOS14 for the list layout, that i am using under iOS14

Is there a way of achieving it?

Note: this is a simple case, but i have many cells, so having 2 different classes for each iOS is not an option

@available(iOS 13, *)
class MyCell: UICollectionViewCell {
    
}

@available(iOS 14, *)
class MyCell: UICollectionViewListCell {
    
}
1

There are 1 answers

1
Chip Jarred On

What you want to do is conditionally compile one or the other, so what you need is something that has this form:

#if os(iOS)
    #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 140000
        @available(iOS 14, *)
        class MyCell: UICollectionViewListCell { }
    #else
        @available(iOS 13, *)
        class MyCell: UICollectionViewCell { }
    #endif
#else
// Maybe cases here for macOS, tvOS, watchOS
#endif