2015-04-07 25 views
0

讓我來描述一下我的問題。找不到會員'CellForItemAtIndexPath'

我編寫了一個名爲CardCell一類從UICollectionViewCell繼承。 在我的其他課程中,MainViewControllerUICollectionView的一個子類。創建了NSMutableArray的一個實例,即items,用於存儲每個單元的數據。

變種項= NSMutableArray的()

self.items = NSMutableArray中(容量:20) 對於i在0 ... 20 { items.addObject( 「物件(I)」) }

items移動到CollectionView的indexPath並準備好調用。

func collectionView(collectionView: UICollectionView!, moveItemAtIndexPath fromIndexPath: NSIndexPath!, toIndexPath: NSIndexPath!) { 
    var thing: NSString = items[fromIndexPath.item] as NSString 
    self.items.removeObjectAtIndex(fromIndexPath.item) 
    self.items.insertObject(thing, atIndex: toIndexPath.item) 
} 

最後,我想用items創建CardCell一個實例。

var cell: CardCell = CardCell(self.collectionView?.cellForItemAtIndexPath(self.collectionView?.indexPathsForSelectedItems().first)) 

接下來,發生了錯誤 「找不到成員 'CellForItemAtIndexPath'」。 我需要說的一件事是那些代碼是從Objective-C版本翻譯的。

Objective-C的版本:

PassCell *cell = (PassCell *)[self.collectionView cellForItemAtIndexPath:[[self.collectionView indexPathsForSelectedItems] firstObject]]; 

請幫我解決這個問題。

非常感謝您的指導和時間。

Ethan Joe

+0

你有沒有在代表中提到過'UICollectionViewDelegateFlowLayout' – Shruti

+0

@Shruti,你的意思是'UICollectionViewDelegate'? 「UICollectionViewDelegateFlowLayout」的需求在哪裏? – itsji10dra

+0

我曾經有過類似的問題。我添加了這個代表,並得到解決。所以試試吧。 – Shruti

回答

1

可能是因爲Objective-C的翻譯出錯了。我不認爲你可以使用UICollectionView實例方法來初始化你的自定義單元格。

在Objective-C代碼中,您將結果轉換爲自定義單元格類型。我相信斯威夫特,你也應該這樣做(注意,我分裂聲明成兩個以提高可讀性):

let indexPath = self.collectionView?.indexPathsForSelectedItems().first as IndexPath 
var cell = self.collectionView?.cellForItemAtIndexPath(indexPath) as CardCell 

注:根據您的定義,你可能需要爲轉型操作as?as!

+0

感謝您的回答。在答案的第二行中會出現另一個錯誤。 Complier說'''這是後面 'self.collectionView' 需要由於被刪除'類型是(UICollectionView,didSelectItemAtIndexPath:NSIndexPath) - >()' –

+0

後我糾正它作爲'變種細胞= self.collectionView .cellForItemAtIndexPath(indexPath如NSIndexPath)? ',它構建併成功運行。 –

+0

我爲'indexPath'添加了第一條語句。感謝您指出詳細信息。 – Mundi