[英]Resizing UIViews in UICollectionViewCells from another UICollectionView
[英]Fill UICollectionViewCells in UICollectionView with data from an array programmatically
我有一个UICollectionView,我想用100个UICollectionViewCells填充它,每个UICollectionViewCells都有自己独特的UILabel,文本从数组中获取。 我想以编程方式执行此操作(不使用Storyboard)。
我已尝试过如下所示,但出于某种原因,只有第一个单元格正确呈现。
// Setting up the UICollectionView
- (void)setupCollectionView {
UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
CGRect newFrame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height * 0.5);
self.collectionView=[[UICollectionView alloc] initWithFrame:newFrame collectionViewLayout:layout];
[self.collectionView setDataSource:self];
[self.collectionView setDelegate:self];
[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
[self.collectionView setBackgroundColor:[UIColor clearColor]];
[self.view addSubview:self.collectionView];
}
//Trying to generate the unique cells with data
- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
cell.backgroundColor = [UIColor yellowColor];
UILabel *label = [[UILabel alloc] initWithFrame: cell.frame];
label.text = [self.array objectAtIndex: indexPath.row];
label.textColor = [UIColor blackColor];
[cell.contentView addSubview:label];
return cell;
}
注意:我的数组大小为100,随机生成数字。
感谢您的帮助:)
谢谢!
数组的框架应该与其单元格的边界相关,而不是与其单元格的框架相关,谁的起源将随着indexPath的增长而增长。 此外,我们不希望无条件地创建标签,因为单元格可以重复使用。 只有当一个标签不存在时才创建标签....
UILabel *label = (UILabel *)[cell viewWithTag:99];
if (!label) {
label = [[UILabel alloc] initWithFrame: cell.bounds]; // note use bounds here - which we want to be zero based since we're in the coordinate system of the cell
label.tag = 99;
label.text = [self.array objectAtIndex: indexPath.row];
label.textColor = [UIColor blackColor];
[cell.contentView addSubview:label];
}
// unconditionally setup its text
NSNumber *number = self.myArrayOfRandomNumbers[indexPath.row];
label.text = [number description];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.