我在使用具有UILabel
的CustomViewCell时遇到一些麻烦。
如果我第一次展示CollectionView
,那么一切看起来都像预期的那样。如果UILabel
只有一行,则标题位于顶部。但是,如果我开始滚动到列表的末尾而不是返回顶部,则所有UILabels
都有两行,有时标题会在中间划分,如
BEFORE:AwesomeTitle
AFTER:Awesom
eTitle
我确定它与reusable Cells
有关,但我不知道我做错了什么......
我为单元格设置textLabel,如:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
MyItem* a = [self.fetchedResultsController.fetchedObjects objectAtIndex:indexPath.row];
CustomSelectionView *bookCell = [collectionView dequeueReusableCellWithReuseIdentifier:CustomSelectionCell_IDENTIFIER forIndexPath:indexPath];
//CELL CONTAINS an UIImage (Cover) and two UILabels (Author, Title)
//get image from storage
NSString* isbn = a.isbn;
NSString* filePath = [_mamPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg", isbn]];
FDIBookCollectionViewCell* __weak weakCell = bookCell;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
NSData* data = [NSData dataWithContentsOfFile:filePath];
UIImage* image = [UIImage imageWithData:data scale:[[UIScreen mainScreen] scale]];
if (!image) {
//... handle
}
if (image && weakCell) {
dispatch_async(dispatch_get_main_queue(), ^{
weakCell.imageView.image = image;
[weakCell.imageView setNeedsDisplay];
});
}
});
//set author and title
bookCell.titelLabel.text = a.titel;
bookCell.titelLabel.numberOfLines = 2; //title label can have two lines
[bookCell.titelLabel sizeToFit];
return bookCell;
}
InterfaceBuilder for Cell:
BookCell.m
@implementation FDIBookCollectionViewCell {}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
//...
- (void)prepareForReuse {
[super prepareForReuse];
self.imageView.image = nil;
}
@end
任何想法?
答案 0 :(得分:1)
你很接近,我认为这个问题与在滚动过程中准备好重复使用单元格有关。你已经在prepareForReuse
中将图像设置为nil这是好的,你应该只需要将标签设置为nil,这样你的方法就变成了:
-(void)prepareForReuse
{
[super prepareForReuse];
self.imageView.image = nil;
self.titelLabel = nil;
}
手指交叉应该有效!
编辑:
在自定义单元格标题中,定义setContent方法和标签变量:
-(void)setContentWithDictionary:(NSDictionary *)content;
@property (nonatomic, strong) UILabel *titelLabel;
然后在您的实施文件中:
-(void)setContentWithDictionary:(NSDictionary *)content
{
//Initialise your labels here
titelLabel = [[UILabel alloc] init];
//Customise label and set text
[titelLabel setText:[content valueForKey:@"CellTitle:]];
}
然后:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
//Most of your current code
//Not tested this line, probably won't work as is but you get the idea!
NSDictionary *cellContent = [NSDictionary dictionaryWithValuesAndKeys:[a.titel], @"CellTitle"];
CustomSelectionView *bookCell = [collectionView dequeueReusableCellWithReuseIdentifier:CustomSelectionCell_IDENTIFIER forIndexPath:indexPath];
[bookCell setContent:cellContent];
return bookCell;
}
对于单元格中的每个其他元素,只需在字典中添加一个新元素即可。这样,每次需要绘制一个单元格时,它都会获得正确的内容,并且标签将以正确的方式设置。
希望这一切都有意义和帮助!
马特