问题:我遇到一个问题,使用estimatedHeightForRowAtIndexPath 和heightForRowAtIndexPath 计算的单元格高度返回错误的高度。具体来说,有时单行文本标签的高度会返回与贴纸相同的高度(高度太大)。或者,图像最终与单行文本标签的高度相同(高度太小)。
理论:我根据消息的类型使用不同的单元格高度。由于有时文本显示为与贴纸相同的高度(固定高度为 150),我想知道在重新使用单元格的地方是否存在错误。或者,我从单元高度缓存中保存/读取的方式存在错误。
奖励: 我至少花了一个月的时间试图弄清楚发生了什么。这不是一个容易的问题。您将收到我永恒的感激之情,以及我可以添加的赏金。
这是一些上下文的代码。一、heightForRowAtIndexPath:
- (CGFloat) tableView: (UITableView *) tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath {
NSNumber *cachedCellHeight = [self.cachedCellHeights objectForKey:[NSString stringWithFormat:@"%u", indexPath.row]];
if([cachedCellHeight floatValue] >= MINIMUM_CELL_HEIGHT) {
// NSLog(@"Retrieving cached cell height (estimatedHeightForRowAtIndexPath): %f for row: %u", [cachedCellHeight floatValue], indexPath.row);
return [cachedCellHeight floatValue];
}
// Cell height is not in the cache (or somehow an invalid height is retrieved), calculate and store it
NSManagedObject *record = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSInteger type = [[record valueForKey:@"type"] integerValue];
NSString *message = [NSString stringWithFormat:@"%@", [record valueForKey:@"message"]];
static NSString *identifier = @"MessagesTableViewCellTextLeft";
switch (type) {
case TypeText:
identifier = @"MessageTypeText";
break;
case TypeImage:
identifier = @"MessageTypeImage";
break;
case TypeSticker:
identifier = @"MessageTypeSticker";
break;
}
static MessagesTableViewCell *cell = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
cell = [self.tableView dequeueReusableCellWithIdentifier: identifier];
});
CGFloat calculatedCellHeight;
UIImage *image = nil;
switch (type) {
case TypeText:
cell.textLabel.text = message;
[cell setNeedsLayout];
[cell layoutIfNeeded];
calculatedCellHeight = [cell.contentView systemLayoutSizeFittingSize: UILayoutFittingCompressedSize].height; // used for multi line labels
break;
case TypeImage:
image = [self getImageFromDocumentsFolder:message];
if (image) {
calculatedCellHeight = [self getImageCellHeight: image]; // calculates height based on aspect ratio of image
}
break;
case TypeSticker:
calculatedCellHeight = 150; // will always be this height
break;
}
/* If the calculation fails and the value is below the minimum cell height, don't store in the cell heights cache */
if(calculatedCellHeight >= MINIMUM_CELL_HEIGHT) {
// NSLog(@"Calculating and storing cell height (estimatedHeightForRowAtIndexPath): %f for row: %u for type: %@", calculatedCellHeight, indexPath.row, identifier);
[self.cachedCellHeights setObject:[NSNumber numberWithFloat:calculatedCellHeight] forKey:[NSString stringWithFormat:@"%u", indexPath.row]];
[self saveCachedHeightsToDisk];
} else {
calculatedCellHeight = [cell.contentView systemLayoutSizeFittingSize: UILayoutFittingCompressedSize].height;
}
return calculatedCellHeight;
}
此外,为了让多行标签起作用,我必须在自定义单元格类中设置一个 preferredMaxLayoutWidth:
- (void) updateConstraints {
[super updateConstraints];
// For multi-line labels, this property is required to word wrap appropriately
// In this case, word wrapping will occur 100 units away from screen edge
textLabel.preferredMaxLayoutWidth = CGRectGetWidth([[UIScreen mainScreen] bounds]) - 100;
}
这是我对单元高度缓存的实现。注意,cachedCellHeights 只是一个合成的 NSDictionary:
- (void) saveCachedHeightsToDisk {
NSArray *directoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if ([directoryPath count] > 0) {
NSString *rebasedPath = [ClientUtilities rebasePathToCurrentDocumentPath:CACHED_CELL_HEIGHTS_FILENAME];
[self.cachedCellHeights writeToFile:rebasedPath atomically:YES];
}
}
- (NSMutableDictionary *) loadCachedHeightsFromDisk {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *filePath = [ClientUtilities rebasePathToCurrentDocumentPath:CACHED_CELL_HEIGHTS_FILENAME];
if (![fileManager fileExistsAtPath:filePath]){
// NSLog(@"Initializing cached cell heights to disk");
return [NSMutableDictionary dictionary];
} else {
// NSLog(@"Loading cached cell heights from disk");
return [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
}
}
请注意,估计的HeightForRowAtIndexPath 和heightForRowAtIndexPath 使用相同的代码。我知道您不应该在estimatedHeight 中进行任何繁重的计算。但是,由于我是从底部堆叠单元格并且它们的高度可能变化很大,因此我必须进行此计算(或从缓存中读取)。否则滚动到底部功能不起作用(它将滚动放置在它认为结束的位置是基于错误的估计高度计算,这是一些没有意义的随机点)。
一个解决方案或任何意见或建议将不胜感激。