0

我有一个UIViewController包含一个CollectionView但输出全白的

在 GridViewController.h

 #import <UIKit/UIKit.h>

 @interface GridViewController : UIViewController <UICollectionViewDataSource,
   UICollectionViewDelegate>{

  }
 @property (nonatomic, strong)UIImageView *imageHeader;
 @property (nonatomic, strong)UIButton * buttonHome;
 @property (nonatomic, strong)UILabel * labelTitle;
 @property (nonatomic, strong)UICollectionView * collectionView;

 //....
 @end

在 GridViewController.m

 - (void)viewDidLoad
 {
    //....
     [self.collectionView registerClass:[UICollectionView class] 
         forCellWithReuseIdentifier:@"Cell"];

      NSLog(@"%@", self.collectionView);//here (null), why?
     self.collectionView.delegate=self;
     self.collectionView.dataSource=self;
    //...
  }

  - (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView
 {
      return 1;
 }

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



- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:
(NSIndexPath *)indexPath{

     NSString *kCellID = @"cellID";
     CollectionViewCellCustom *cell = [cv dequeueReusableCellWithReuseIdentifier:kCellID forIndexPath:indexPath];
    cell.imageView.backgroundColor =[UIColor greenColor];


    return cell;
 }
4

2 回答 2

4

我在您的代码中没有看到任何出口。所以我假设您尝试以编程方式创建它。为此,您应该这样做

UICollectionViewFlowLayout *layout= [[UICollectionViewFlowLayout alloc]init];
self.collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
[self.view addSubView:self.collectionView];  
 [self.collectionView registerClass:[UICollectionViewCell class]
        forCellWithReuseIdentifier:@"Cell"];
 self.collectionView.delegate=self;
 self.collectionView.dataSource=self;

在您的代码中,我可以看到您在registerClass:[UICollectionView class]做错registerClass:[UICollectionViewCell class]的事。

改变

    [self.collectionView registerClass:[UICollectionView class]forCellWithReuseIdentifier:@"Cell"];

  [self.collectionView registerClass:[UICollectionViewCell class]forCellWithReuseIdentifier:@"Cell"];

您使用不同单元格 ID 的另一个错误是注册和出队。让它一样。使用 id Cell注册单元并尝试使用cellID进行双端队列

于 2013-03-13T11:24:01.533 回答
1

对于示例代码,您可以参考这个

希望这会帮助你。

祝一切顺利 !!!

于 2013-03-13T11:00:22.327 回答