我在故事板中有一个UICollectionView,位于UICollectionViewController中。 UICollectionViewController链接到我的自定义class MasterViewController: UICollectionViewController, UICollectionViewDataSource, UICollectionViewDelegate
,它的委托和数据源在故事板中链接到此类。
我在故事板中有一个原型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 :(得分:5)
我遇到了同样的问题。 Raywenderlich Swift manual帮助了我。我在这里复制MyCollectionViewController
。
UICollectionViewCell
类。UICollectionViewCell
。viewDidLoad()
。 registerClass:forCellWithReuseIdentifier:
在UICollectionViewDelegateFlowLayout
中使用collectionView:layout:sizeForItemAtIndexPath:
设置单元格项目大小。
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
}