2016-05-17 161 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之後不需要執行。

相關問題