2014-02-25 36 views
1

我有一個簡短的問題。我想以編程方式創建一個ViewController,它具有UICollectionView,並將其添加到ScrollView。如果我使用Interfacebuilder執行此操作,則一切正常。但創建實例並以編程方式添加它不起作用,CollectionView不會顯示。這裏是我的代碼的一部分:創建視圖控制器+的CollectionView程序並將其添加到滾動型

ViewController.m

ViewControllerCell* Cell = [[ViewControllerCell alloc]init]; 
[_contentScrollView addSubview:Cell.view]; 

ViewControllerCell.m

- (void)viewDidLoad{ 

    [super viewDidLoad]; 

    [self.view addSubview:self.collectionView]; 
    [self.view setBackgroundColor:[UIColor lightGrayColor]]; 
} 

淺灰色的背景出現了,所以我認爲,該子視圖中添加,但不知何故我的collectionview沒有出現。任何人都可以幫我嗎?

+0

是您的滾動視圖的contentsize夠大嗎? – iPP

+0

嗯,很好的問題,與interfacebuilder我剛創建一個容器視圖,並將其CustomClass設置爲ViewControllerCell。 但我只是用了滾動水平滾動的的CollectionView應該做垂直滾動,它的工作原理,如果我米使用Interface Builder – seniorbenelli

+0

第一件事,ScollView內滾動視圖是壞的。關於你的問題,從'ViewController.m'發佈一些更多的代碼,你在那裏創建你的滾動視圖'contentScrollView' – iPP

回答

1

檢查您要添加的委託方法正確

@interface ViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout> 
{ 
    UICollectionView *_collectionView; 
} 

- (void)viewDidLoad { 
    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init]; 
    _collectionView=[[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout]; 
    [_collectionView setDataSource:self]; 
    [_collectionView setDelegate:self]; 

    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"]; 
    [_collectionView setBackgroundColor:[UIColor redColor]]; 

    [self.view addSubview:_collectionView]; 

    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 
} 

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { 
    return 10; 
} 

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { 
    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath]; 

    cell.backgroundColor=[UIColor blueColor]; 
    return cell; 
} 

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return CGSizeMake(40, 40); 
} 
+0

我剛試過這個,但它不起作用。我使用這個:https://github.com/chiahsien/CHTCollectionViewWaterfallLayout 也許這是問題? – seniorbenelli

+0

我不知道爲什麼,但如果我把這個ViewControllerCell * Cell;在@implementation {...}中它確實有效。有人可以向我解釋這個嗎? – seniorbenelli

+0

你能展示更多代碼嗎?你的代碼不清楚。 ViewController是你的CollectionView?並在添加到_contentScrollView之前設置您的ViewController框架 –

相關問題