我试图UICollectionView
通过以编程方式构建它来教自己如何使用它。我按照一些教程创建了一个大小为 500 x 500 的示例集合视图,每个单元格为 245 x 45。到目前为止,我能够看到集合视图,但它不包含任何单元格,我不知道为什么。这是我所做的:
//子类 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?