【问题标题】:UICollectionView does not load-iOSUICollectionView 不加载-iOS
【发布时间】:2013-03-13 10:57:48
【问题描述】:

我有一个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;
 }

【问题讨论】:

  • 你在使用xib吗?检查插座是否连接
  • 我没有 IBOutlet,一切都是靠代码完成的

标签: ios uiviewcontroller uicollectionview uicollectionviewcell


【解决方案1】:

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

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

进行 deque

【讨论】:

  • Now exit: *** Assertion failure in -[UICollectionView _dequeueReusableViewOfKind:withIdentifier:forIndexPath:]
  • 您使用不同的单元格 id 的“Cell”和“cellId”使其相同
  • 我更正了它,但现在退出:由于未捕获的异常 'NSInvalidArgumentException' 导致应用程序终止,原因:'UICollectionView 必须使用非零布局参数初始化'
  • 我认为您没有创建布局对象。见我上面的回答。您应该在创建集合视图之前创建布局
【解决方案2】:

示例代码可以参考this

希望这会对你有所帮助。

一切顺利!!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-31
    相关资源
    最近更新 更多