我有一個相當大的應用程序,它有很多集合視圖。大多數集合視圖對數據源和流佈局代表具有相同的實現(相同的大小,邊距等)。我正在嘗試創建一個提供UICollectionViewDataSource和UICollectionViewDelegateFlowLayout的默認實現的協議。這是我的代碼。擴展UICollectionViewDataSource協議以添加默認實現
protocol TiledCollectionView{}
extension UICollectionViewDataSource where Self: TiledCollectionView{
//default implementation of the 3 methods to load the data ...
}
extension UICollectionViewDelegateFlowLayout where Self: TiledCollectionView {
//default implementation for layout methods to set default margins etc...
}
class MyViewController: UIViewController, TiledCollectionView, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
// the rest of the required logic for view controller
// here I Don't implement any CollectionView methods since I have provided the default implementation already
}
的問題是,編譯器會抱怨說MyViewController不符合UICollectionViewDataSource。這不應該是這樣,因爲我清楚地說如果類型是TiledCollectionView,添加默認實現。
有人可以幫忙嗎?
這似乎是添加裝飾器的好方式,就像Python或Java中的裝飾器一樣。繼續添加定義特定行爲和單個方法調用的協議(useProtocolFor ...)可以添加該行爲。 – suparngp
'@ suparngp'並非如此。如果你在協議中聲明瞭一個變量('var handler:CollectionViewProtocolHandler!') - 你不能在擴展中實現它 - 所以你必須手動將它添加到你的類中。至少你不能在沒有它的情況下建立你的項目。如果Apple向協議添加了聲明塊,那麼當您像Ruby一樣繼承它時會很好,所以您可以在其中看到所有擴展變量和函數,並且可以選擇重寫它們。 – katleta3000