显示黑屏而不是UICollectionView

我试图重新实现在这里看到的不定式滚动UICollectionView 。 对我而言缺less的东西:

ViewController.h

 @interface ViewController : UIViewController<UICollectionViewDataSource, UICollectionViewDelegate> @end 

DataCell.h

 @interface DataCell : UICollectionViewCell @property (nonatomic, strong) UILabel *label; @end 

DataCell.m

 #import "DataCell.h" @implementation DataCell -(instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if(self){ self.label = [[UILabel alloc] initWithFrame:self.bounds]; self.autoresizesSubviews = YES; self.label.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); self.label.textAlignment = NSTextAlignmentCenter; self.label.adjustsFontSizeToFitWidth = YES; [self addSubview:self.label]; } return self; } @end 

CustomCollectionView.h:

 @interface CustomCollectionView : UICollectionView @end 

对于整个项目,我使用了一个故事板和一个普通的UIViewController 。 在这个视图控制器上,我在Interface Builder中添加了一个UICollectionView 。 我从集合视图与我的视图控制器连接出口,并设置数据源和委托方法再次我的视图控制器。 我还在Interface Builder中设置了UICollectionViewCell的自定义类和重用标识符。

所以一切都应该工作,但我只能得到一个黑屏。 我错过了什么? 你可以在这里下载整个项目。

你configuration正确的CollectionView,只是你忘了标签的颜色:)

  [self.label setTextColor:[UIColor whiteColor]]; 

在这里输入图像说明

希望能帮助到你!

我遇到过同样的问题。 黑屏似乎是集合视图无法显示数据的指标。 尝试更改集合视图的背景颜色,如果显示的是已更改的颜色,则您的集合视图正在工作。 然后添加一些imageview到带有标签的集合视图(例如,给图像视图的标签值赋予一个值100),并用cellforItemAtIndexPath将图像设置为图像视图。 (你可以用自定义的单元格来做到这一点,但现在,为了使集合视图正常工作,imageview标签的赋值更合适)

 UIImageView * ImageView = (UIImageView *)[cell viewWithTag:100]; ImageView.image = [UIImage imageNamed:[images objectAtIndex:indexPath.row]]; 

您需要在故事板中手动设置集合视图的背景颜色。

默认情况下它是黑色的(虽然在故事板编辑器中没有显示)

在这里输入图像说明

我碰巧收集视图和收集视图单元都有透明的背景

在Swift中,

 self.label.textColor = UIColor.whiteColor() 
 [self.collectionView registerNib:[UINib nibWithNibName:@"ProductCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"ProductCollectionViewCell"]; self.collectionView.backgroundColor = [UIColor clearColor];