0

我正在以編程方式創建UICollectionViewUICollectionViewCell未出現

作爲一個聲明,我跟着這個教程:http://randexdev.com/2014/07/uicollectionview/

所以我的設置如下:

我有與由ViewControllerA控制的UIScrollView故事板。

在一個單獨的類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,但沒有任何細胞。

任何提示我做錯了什麼?

+0

你可以設置你的CollectionView斷點:cellForItemAtIndexPath:功能,看看它是否被調用? – dirkgroten

+0

@dirkgroten我已經做了。它被稱爲。 – Phytochrome

回答

0

的問題是,我沒有設置ViewControllerchildViewControllerviewControllerA

self.addChildViewController(collectionViewController) 
collectionViewController.didMoveToParentViewController(self) 
1

可能是-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath已遺失!

+0

我剛剛嘗試並添加了'func collectionView(collectionView:UICollectionView,佈局collectionViewLayout:UICollectionViewLayout,sizeForItemAtIndexPath indexPath:NSIndexPath) - > CGSize {return CGSizeMake(90,120)}',但它沒有改變任何東西。 – Phytochrome

+0

您的視圖控制器是UICollectionViewController的子類嘗試將其更改爲UIViewController或嘗試self.collectionView = yourCollectionView – iOS77

+0

不可以。沒有任何變化。 – Phytochrome