UICollectionViewCell没有出现

时间:2016-04-07 12:02:48

标签: ios swift uicollectionview uicollectionviewcell uicollectionviewlayout

我正在以编程方式创建UICollectionView

作为免责声明,我遵循了本教程:http://randexdev.com/2014/07/uicollectionview/

所以我的设置如下:

我有一个UIScrollView的故事板,由ViewControllerA控制。

在单独的班级CustomCollectionViewController中,我有以下代码:

import Foundation
import UIKit

class CustomCollectionViewController : UICollectionViewController, UICollectionViewDelegateFlowLayout {

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {

        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
        layout.itemSize = CGSize(width: 90, height: 120)

        super.init(collectionViewLayout: layout)

        collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
        //collectionView = UICollectionView(frame: CGRectMake(0, 0, 500, 500), collectionViewLayout: layout)
        collectionView!.dataSource = self
        collectionView!.delegate = self
        collectionView!.backgroundColor = UIColor.redColor()
        collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
        self.view.addSubview(collectionView!)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

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

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath)
        cell.backgroundColor = UIColor.greenColor()
        return cell
    }
}

在我的ViewControllerA我有这段代码

let collectionViewController: CustomCollectionViewController = CustomCollectionViewController(nibName: nil, bundle: nil)
collectionViewController.view.frame.origin = CGPointMake(scrollViewWidth*3, 0)

scrollView.addSubview(collectionViewController.view)

如果在模拟器中运行,我可以看到UICollectionView的红色背景,但没有任何细胞。

任何提示我做错了什么?

2 个答案:

答案 0 :(得分:1)

可能缺少-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

答案 1 :(得分:0)

问题是我没有在ViewController

中将childViewController设置为viewControllerA
self.addChildViewController(collectionViewController)
collectionViewController.didMoveToParentViewController(self)