我试图通过以编程方式构建它来教自己如何使用UICollectionView
。我已经按照一些教程创建了一个大小为500 x 500的示例集合视图,每个单元格为245 x 45.到目前为止,我能够看到集合视图,但它不包含单元格,我不知道为什么。下面是我做的:以编程方式创建UICollectionView
//子类UICollectionViewLayout
@interface LabelCVLayout : UICollectionViewLayout
@property (nonatomic) UIEdgeInsets itemInsets;
@property (nonatomic) CGSize itemSize;
@property (nonatomic) CGFloat interItemSpacingY;
@property (nonatomic) NSInteger numberOfColumns;
@end
@implementation LabelCVLayout
- (id)init
{
self = [super init];
if (self) {
[self setup];
}
return self;
}
- (void)setup
{
self.itemInsets = UIEdgeInsetsMake(22.0f, 22.0f, 13.0f, 22.0f);
self.itemSize = CGSizeMake(245.0f, 45.0f);
self.interItemSpacingY = 12.0f;
self.numberOfColumns = 3;
}
@end
//这显示集合视图
@interface TempViewController() <UICollectionViewDataSource, UICollectionViewDelegate>
@property (strong, nonatomic) UICollectionView *collectionView;
@end
@implementation TempViewController
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView
numberOfItemsInSection:(NSInteger)section
{
return 4;
}
//THE BELOW DELEGATE METHOD DOES NOT GET CALLED!
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"newCell" forIndexPath:indexPath];
cell.backgroundColor = [UIColor whiteColor];
UILabel *testLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, cell.size.width, cell.size.height)];
testLabel.font = [UIFont fontWithName:ProximaNovaSemibold size:15];
testLabel.text = [NSString stringWithFormat:@"Label %i", indexPath.row];
testLabel.clipsToBounds = YES;
testLabel.backgroundColor = [UIColor clearColor];
testLabel.textColor = [UIColor blackColor];
testLabel.textAlignment = NSTextAlignmentLeft;
[cell addSubview:testLabel];
NSLog(@"test!"); //does not print!
return cell;
}
- (void)viewDidLoad
{
[super viewDidLoad];
LabelCVLayout *flowLayout = [[LabelCVLayout alloc]init];
self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,0,500,500) collectionViewLayout:flowLayout];
self.collectionView.backgroundColor = [UIColor redColor];
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"newCell"];
[self.view addSubview:self.collectionView];
}
@end
奇怪的视图控制器,设置断点后,我发现numberOfSections
和numberOfItemsInSection
数据源方法正在调用,但cellForItemAtIndexPath
方法没有被调用。
我想知道是否 1)任何人都可以看到我错过了什么?和2)如果我以后想要创建一个集合视图,根据单元格大小和集合视图大小的大小约束将适当数量的单元格添加到行中(即,我不想定义一个固定的数字的列),我必须继承UICollectionViewFlowLayout而不是UICollectionViewLayout吗?
是的,我打算建议更改为'UICollectionViewFlowLayout'子类,因为它看起来像是在自定义流布局之后。 – Fogmeister
谢谢!切换到UICollectionViewFlow布局解决了这个问题,你提出的方法正是我所期待的。 – jac300