2014-11-21 144 views
4

我在故事板中的UICollectionView中有一个UICollectionViewController。 UICollectionViewController链接到我的自定义class MasterViewController: UICollectionViewController, UICollectionViewDataSource, UICollectionViewDelegate,它的委托和数据源在故事板中链接到这个类。UICollectionViewCell与故事板

我有一个原型UICollectionViewCell在故事板,与标识符“了myCell”,从我的自定义class Cell: UICollectionViewCell

cellForItemAtIndexPath方法,在该行的应用程序崩溃:let cell:Cell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", forIndexPath: indexPath) as Cell

我没有找到原因。我还没有实现registerClass:forCellWithReuseIdentifier:方法,故事板的标识符正好是“MyCell”,我查了很多次,委托和数据源都链接到了正确的类。

当应用程序崩溃,没有什么是打印到控制台上,只是 “(LLDB)”

这里是我的代码:

class MasterViewController: UICollectionViewController,UICollectionViewDataSource,UICollectionViewDelegate { 


var objects = [ObjectsEntry]() 

@IBOutlet var flowLayout: UICollectionViewFlowLayout! 

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


override func viewDidLoad() { 
    super.viewDidLoad() 

    flowLayout.itemSize = CGSizeMake(collectionView!.bounds.width - 52, 151) 

} 



// MARK: - Collection View 

override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { 
    return 1 
} 

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

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
    let cell:Cell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", forIndexPath: indexPath) as Cell 

    return cell 

} 
+0

这里是通过得到一个基本的集合视图和集合视图小区设立的散步:http://stackoverflow.com/questions/31735228/how-to-make-a-simple-collection - 视图 - 与-迅速 – Suragch 2015-07-30 22:45:28

回答

4

我有同样的问题。 Raywenderlich Swift manual帮助了我。我在这里复制MyCollectionViewController

  • 标识符必须在控制器和故事板中匹配。
  • 创建自定义UICollectionViewCell类。
  • 在故事板中设置此UICollectionViewCell
  • 请勿拨打viewDidLoad()
  • 不要在collectionView:layout:sizeForItemAtIndexPath:调用registerClass:forCellWithReuseIdentifier:
  • 设置单元格的商品尺寸与UICollectionViewDelegateFlowLayout

    import UIKit 
    
    class MyCollectionViewController: 
    UICollectionViewController, 
    UICollectionViewDelegateFlowLayout { 
    
    private let reuseIdentifier = "ApplesCell" 
    
    // MARK: UICollectionViewDataSource 
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
        return 1 
    } 
    
    override func collectionView(collectionView: UICollectionView, 
          cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as MyCollectionViewCell 
        cell.backgroundColor = UIColor.redColor() 
        cell.imageView.image = UIImage(named: "red_apple") 
        return cell 
    }