UICollectionView单元格绘制在左上角



这是我第一次使用UICollectionView。

据我所知,我已经把一切都安排好了。我在UICollectionView的出列函数的工作方式上遇到了一些困难,但我想我已经克服了。当我不知道是否会调用initWithFrame或prepareForReuse时,设置我的自定义单元格类是很棘手的。

我很确定问题出在prepareForReuse函数中,但哪里是问题所在。

发生的情况是,这些单元格显然会在集合视图的左上角随机绘制,有些单元格将不在网格中所属的位置。(见所附图片)

当反弹、滚动和缩放(从而导致重复使用)时,就会出现问题。随机地,一张幻灯片将出现在左上角,其他幻灯片将随机地从网格中消失。

(我需要更多的代表来发布图片。嗯。:|如果你能帮我,我会把图片发电子邮件给你。bmantzey@mac.com)

-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
Slide* thisSlide = [_presentation.slidesInEffect objectAtIndex:indexPath.row];
[BuilderSlide prepareWithSlide:thisSlide];
BuilderSlide* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PlainSlide" forIndexPath:indexPath];
return cell;}

我使用一个静态方法来设置Slide对象,它包含准备异步下载或从磁盘缓存中检索图像所需的数据。

很简单:

+(void)prepareWithSlide:(Slide*)slide{
if(s_slide)
[s_slide release];
s_slide = [slide retain];}

我不确定这样做是否是一个很大的禁忌,但在我的自定义Cell类中,我在initWithFrame块中调用prepareForReuse,因为我需要相同的设置代码:

-(id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if(self)
{
[self prepareForReuse];
}
return self;}

这是prepareForReuse函数:

-(void)prepareForReuse{
CGSize size = [SpringboardLayout currentSlideSize];
[self setFrame:CGRectMake(0, 0, size.width, size.height)];
self.size = size;
// First remove any previous view, so as not to stack them.
if(_builderSlideView)
{
if(_builderSlideView.slide.slideID == s_slide.slideID)
return;
[_builderSlideView release];
}
for(UIView* aView in self.contentView.subviews)
{
if([aView isKindOfClass:[BuilderSlideView class]])
{
[aView removeFromSuperview];
break;
}
}
// Then setup the new view.
_builderSlideView = [[BuilderSlideView alloc] initWithSlide:s_slide];
self.builderCellView = _builderSlideView;
[s_slide release];
s_slide = nil;
[self.contentView addSubview:_builderSlideView];
if([SlideCache isImageCached:_builderSlideView.slide.slideID forPresentation:_builderSlideView.slide.presentationID asThumbnail:YES])
{
[_builderSlideView loadImageFromCache];
}
else
{
[_builderSlideView loadView];
}}

最后,当幻灯片图像被下载后,会发布一个通知(我计划将其更改为代理呼叫)。通知只是重新加载已接收更新的单元格。这是通知代码:

-(void)didLoadBuilderCellView:(NSNotification*)note{
BuilderCellView* cellView = [[note userInfo] objectForKey:@"cell"];
BuilderSlideView* slideView = (BuilderSlideView*)cellView;
NSIndexPath* indexPath = [self indexPathForSlide:slideView.slide];
if(indexPath)
[self.collectionView reloadItemsAtIndexPaths:[NSArray arrayWithObject:indexPath]];}

请注意,幻灯片对象存在于模型中。

关于这个问题的原因有什么想法吗?提前感谢!

导致单元格从左上角绘制和/或消失的问题是由后台线程上的无限递归引起的。简单明了,我没有正确、安全地实现延迟加载。为了解决这个问题,我回到绘图板上再试了一次。懒惰加载算法的正确实现起到了作用。

最新更新