2017-01-11 53 views
0

因此,我對swift很陌生,試圖創建一個自定義UiCollectionView,您可以水平滾動瀏覽,當點擊按鈕時,可以將相機膠捲中的圖像添加到陣列集合視圖中的圖像。這是我迄今爲止所遇到的問題,並且遇到了一些問題。我曾嘗試在線觀看視頻,但仍然收到錯誤,所以我不知道自己做錯了什麼。我有一些加載到我的資產文件夾中的蘋果產品圖像,我將在數組中使用這些圖像作爲collectionView。每個圖像將在一個colletionViewCell中。Swift 3中的自定義UICollectionView無法正常工作

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { 

    @IBOutlet weak var collectionView: UICollectionView! 

    let imageArray = [UIImage(named: "appleWatch"), UIImage(named: "iPhone"), UIImage(named: "iPad"), UIImage(named: "iPod"), UIImage(named: "macBook")] 


    func numberOfSections(in collectionView: UICollectionView) -> Int { 

     return 1 

    } 


    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 

     return self.imageArray.count 


    } 


    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 

     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! UICollectionViewCell 


     cell.ourImage?.image = self.imageArray[indexPath.row] 

     return cell 

    } 
} 

在這裏給我一個錯誤cell.ourImage?.image = self.imageArray[indexPath.row]並說「值類型UICollectionViewCell沒有成員‘ourImage’」即使我叫出口ourImage另一個UICollectionViewCell迅速文件。我檢查了Main.storyboard,我想我已經正確地命名了所有的類,並將它們分配給了collectionViewCell和標識符。我刪除了這一行,它編譯得很好,但是每當應用程序運行時屏幕上都沒有顯示,所以我的圖像可能會出現問題。有人有任何想法嗎?你將如何去創建一個自定義的UiCollection視圖?我有正確的想法嗎?

+0

什麼是您的收藏查看單元格類名稱? –

+1

這個:'as! UICollectionViewCell'告訴編譯器只使用'UICollectionViewCell'中定義的對象的一部分。你真的想告訴它把'cell'作爲你的自定義類的一個實例。 –

+0

將您的自定義單元名稱從UICollectionViewCell更改爲任何其他自定義名稱 –

回答

2

而不是鑄造出隊細胞UICollectionViewCell,您需要將其視爲您的自定義UICollectionViewCell子類。

if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "YourReuseIdentifier", for: indexPath) as? YourCustomCollectionViewCell { 
    // set the cell's custom properties 
} 

您還可以強制使用as! YourCustomCollectionViewCell演員,但我個人不喜歡這樣做。

+0

非常感謝。有效! –

相關問題