【发布时间】:2015-02-16 18:33:20
【问题描述】:
我正在使用uicollectionview 创建一个类似滚动视图的轮播。我认为uicollectionview 是这个用例的最佳方法。我能够在uicollectionview 内渲染uicollectionviewcell,但问题是,当我滚动uicolectionview 时,后面的单元格将消失,最后所有单元格都变黑了。另一个问题是单元格在其边界完全位于 Carousel 内时才会加载。
这就是我在cellForItemAtIndexPath 委托方法中设置我的uicollectionviewcell 的方式
NSString *urlString = [NSString stringWithFormat:BASE_URL, panoid, heading, pitch];
NSURL *panoUrl = [NSURL URLWithString:urlString];
//WIDTH calculated based on screen size, roughly about three cells per screen.
CGFloat WIDTH = collectionView.frame.size.width / 3;
UIImageView *panoImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 133.3)];
// add padding to imageview
panoImg.bounds = CGRectInset(panoImg.frame, 2, 2);
// do I need GCD to do async process here? the images are all loaded from urls. not sure if this will cause a problem.
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSData *data = [NSData dataWithContentsOfURL:panoUrl];
dispatch_async(dispatch_get_main_queue(), ^{
[panoImg setImage:[UIImage imageWithData:data]];
});
});
seeInsideCollectionViewCell *cell = [_panoCarousel dequeueReusableCellWithReuseIdentifier:@"panoCarouselCell" forIndexPath:indexPath];
cell.frame = CGRectMake(indexPath.item * WIDTH + 4, 0, WIDTH, 133.3);
cell.backgroundColor = [UIColor blackColor];
[cell addSubview: panoImg];
UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(4, 4, WIDTH, 15)];
[label setBackgroundColor: [UIColor colorWithRed:0.63 green:0.63 blue:0.63 alpha:0.5]];
[label setFont: [UIFont fontWithName:@"Roboto-Light" size:10.0]];
[label setText: _BussinessViewsNames[indexPath.item]];
[cell addSubview:label];
return cell;
任何建议,单元格都已加载,只是加载不是无缝和流畅,我已附上一个 gif 来演示这里的问题。
【问题讨论】:
-
使用 GCD 进行抓取是正确的。集合视图的布局应该设置单元格的位置和大小,因此您应该省略以
cell.frame = ...开头的行。如果您仍然遇到问题,请告知使用您正在使用的布局,以及您是否在单元子类中执行任何特殊操作。 -
顺便说一句,如果您删除图像,滚动时您会开始在每个单元格中看到很多标签重叠。您不应该向 cellForItemAtIndexPath 中的单元格“添加”视图。你应该继承 UICollectionviewcell
标签: ios objective-c uicollectionview uicollectionviewcell