2016-05-17 128 views
1

开始练习Swift。在singleViewController我试图做一个UICollectionView。在故事板中,我设置了dataSourcedelegate。在这里,我得到的错误:类型不符合协议Swift

'UICollectionView' does not conform to protocol 'UICollectionViewDataSource'

import UIKit 

class galeriacontroler: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource{ 

    @IBOutlet weak var collectionview: UICollectionView! 

    let fotosgaleria = [UIImage(named: "arbol3"), UIImage(named:"arbol4")] 

    override func viewDidLoad() { 
     super.viewDidLoad() 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
    } 

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
     return self.fotosgaleria.count 
    } 

    func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { 
     let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cellImagen", forIndexPath:indexPath) as! cellcontroler 

     cell.imagenView2?.image = self.fotosgaleria[indexPath.row] 
    } 

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 
     self.performSegueWithIdentifier("showImage", sender: self) 
    } 

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
     if segue.identifier == "showImage" 
     { 
      let indexPaths = self.collectionview!.indexPathsForSelectedItems() 
      let indexPath = indexPaths![0] as NSIndexPath 

      let vc = segue.destinationViewController as! newviewcontroler 

      vc.image = self.fotosgaleria[indexPath.row]! 
     } 
    } 
} 

回答

2

UICollectionViewDataSource有两个必需的方法 - collectionView(_:numberOfItemsInSection:)collectionView(_:cellForItemAtIndexPath:),其中只有一个执行。

您需要添加一个实现。collectionView(_:cellForItemAtIndexPath:)来解决这个问题:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath:NSIndexPath)->UICollectionViewCell { 
    var cell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", forIndexPath: indexPath) as CollectionCell 
    ... // Do more configuration here 
    return cell 
} 
1

当您导入UICollectionViewDataSource必须实现cellForItemAtIndexPath方法

添加以下方法给您的代码:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath:NSIndexPath)->UICollectionViewCell { 

let cell = collectionView.dequeueReusableCellWithReuseIdentifier("imagesCellIdentifier", forIndexPath:indexPath) as! cellcontroler 
cell.secondImageView?.image = self.photosGalleryArray[indexPath.row] 

return cell 
} 

willDisplayCell之后不需要执行。

相关问题