从未调用过cellForItemAtIndexPath

时间:2015-10-28 23:06:59

标签: ios swift uicollectionview

我在故事板中添加了UICollectionView UIViewController

它包含UICollectionViewCell个类BookCell和可重复使用的标识符BookCell

bookArray在前一个ViewController

prepareForSegue方法中传递

cellForItemAtIndexPath永远不会被调用。我试图在Storyboard和BookCollectionVC中声明viewDidLoad作为委托和dataSource,正如您所看到的那样,但这并没有改变任何内容。

我已经阅读了多个与单元格大小相关的SO答案,该部分中的项目数,以及声明delegatedataSource的多种方式,并尝试/双重检查了所有这些答案。

有什么想法吗?

class BookCollectionVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    @IBOutlet weak var collection: UICollectionView!

    var bookArray = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

//        collection.delegate = self
//        collection.dataSource = self
    }

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

        if let cell = collectionView.dequeueReusableCellWithReuseIdentifier("BookCell", forIndexPath: indexPath) as? BookCell {

            // This never gets called
            let bookIsbn = bookArray[indexPath.row]
            cell.configureCell(bookIsbn)
            return cell

        } else {

            return UICollectionViewCell()
        }
    } 

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

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

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        let screenSize: CGRect = UIScreen.mainScreen().bounds
        let screenWidth = screenSize.width
        let cellWidth = screenWidth / 4

        return CGSizeMake(cellWidth,cellWidth)
    }

1 个答案:

答案 0 :(得分:0)

作为测试,请勿使用if-let。只需获取单元格值并打印即可。它的类型是什么?您是否已将单元格正确分配为StoryBoard中的自定义类(BookCell)?