2016-08-15 82 views
2

我正在嘗試投射以下內容,但不斷提出下面的錯誤。UICollectionViewLayout子類強制轉換爲子類

我想達到以下,其正常工作的目標C版本:

LSSwipeToDeleteCollectionViewLayoutUICollectionViewFlowLayout子類,寫在客觀C.

目標C:

LSSwipeToDeleteCollectionViewLayout *layout = (LSSwipeToDeleteCollectionViewLayout *)self.collectionView.collectionViewLayout; 

Swift:

let layout : LSSwipeToDeleteCollectionViewLayout = (self.collectionView.collectionViewLayout as AnyObject) as! LSSwipeToDeleteCollectionViewLayout 
     layout.swipeToDeleteDelegate = self 

無法將類型'UICollectionViewFlowLayout' (0x111edda00)的值轉換爲'LSSwipeToDeleteCollectionViewLayout'(0x11040e3c0)。

回答

0

通常你會只是做:

let layout = self.collectionView.collectionViewLayout as! LSSwipeToDeleteCollectionViewLayout

你確定你的時候,你初始化第一次創建LSSwipeToDeleteCollectionViewLayout實例並將其設置爲在UICollectionView.init(frame:collectionViewLayout:)方法collectionViewLayout參數集合視圖?

+0

你好,你的意思是關於你的答案的第二部分? –

+0

當你創建一個集合視圖時,你必須設置負責佈局的類,它必須是'LSSwipeToDeleteCollectionViewLayout',否則你將得到默認的'UICollectionViewFlowLayout'類,這可能是你的類型轉換失敗的原因。根據創建集合視圖的方式,您可以將佈局類設置爲在您的筆尖中,或者直接在代碼中作爲「UICollectionView」初始化程序的參數。 – par