2017-01-11 52 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

非常感谢。有效! –

相关问题