我正在尝试使用具有UIImageView
背景的自定义单元格创建一个简单的集合视图。它看起来像:
这是我的代码:
ViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
[self.collectionView registerClass:[MyCell class] forCellWithReuseIdentifier:@"MY_CELL"];
leftInset = rightInset = 0;
numberOfDays = 31;
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 200;
}
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section
{
return numberOfDays;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{
MyCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"MY_CELL" forIndexPath:indexPath];
if(indexPath.row < 10)
cell.imageView.image = [UIImage imageNamed:@"no"];
else if(indexPath.section%3==1)
{
cell.imageView.image = [UIImage imageNamed:@"ok"];
}
else if(indexPath.section%3==2)
{
cell.imageView.image = [UIImage imageNamed:@"sa"];
}
else{
cell.imageView.image = [UIImage imageNamed:@"happy_vote"];
}
return cell;
}
#pragma mark – UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return CGSizeMake(CELL_DIM, CELL_DIM);
}
- (UIEdgeInsets)collectionView:
(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
// top left bottom right
return UIEdgeInsetsMake(5, leftInset, 0, 0);
}
我的细胞
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
NSLog(@"Init with frame!");
self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, frame.size.width, frame.size.height)];
[self.contentView addSubview:self.imageView];
[self.imageView setBackgroundColor:[UIColor redColor]];
}
return self;
}
它适用于集合视图中的大约 10 个部分。问题是当我想添加更多部分时,垂直滚动开始移动得很慢。我注意到所有单元格都是一次分配的。我正在寻找一种方法来使这对资源更加友好,并让滚动连续移动而不是缓慢和滞后。你能告诉我如何处理资源分配以避免这个问题吗?谢谢你。
PS:我尝试从单元格背景中删除图像视图,并在该方法中cellForItemAtIndexPath:
为单元格设置背景颜色,但同样,在 10 个或更多部分之后,它的移动速度非常慢。