我有一个应用程序,它显示一个 TableView,顶部有两个相对静态的单元格,然后是一系列包含标签和分段控件的自定义单元格。这些单元格的高度需要根据标签中的文本数量而变化。
我在 cellForRowAtIndexPath 中计算所需的单元格高度,将值存储在数组中,然后在 heightForRowAtIndexPath 中使用该数组中的值。但是,似乎首先调用了 heightForRowAtIndexPath,因此我所有的行高都是 0/nil。
当在配置单元格之前需要知道单元格高度时,如何根据单元格的特定内容指定行高?
来自 cellForRowAtIndexPath 的片段:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger currentIndex = indexPath.item;
if (indexPath.item == 0){
static NSString *CellIdentifier = @"MeasurementCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
[self.cellHeightList insertObject:[NSNumber numberWithInt:44] atIndex:currentIndex];
return cell;
} else if (indexPath.item == 1){
if (self.dataController.isScoreAvailable){
static NSString *CellIdentifier = @"ScoreCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
[self.cellHeightList insertObject:[NSNumber numberWithInt:46] atIndex:currentIndex];
return cell;
} else {
static NSString *CellIdentifier = @"ScoreCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryNone;
[self.cellHeightList insertObject:[NSNumber numberWithInt:0] atIndex:currentIndex];
return cell;
}
} else if (indexPath.item > 1){
NSInteger labelWidth = [UIScreen mainScreen].applicationFrame.size.width - 140; //80 for segment + 3*20 for margins & spacing
CGSize maxSize = CGSizeMake(labelWidth, MAXFLOAT);
CGSize labelSize;
static NSString *CellIdentifier = @"QuestionCell";
InterviewQuestionCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
InterviewQuestion *questionAtIndex = [self.dataController objectInListAtIndex:(indexPath.item-2)];
cell.questionLabel.text = questionAtIndex.questionText;
labelSize = [cell.questionLabel.text sizeWithFont:[UIFont systemFontOfSize:12.0] constrainedToSize:maxSize lineBreakMode:NSLineBreakByWordWrapping];
CGRect labelFrame = CGRectMake(0, 0, labelWidth, labelSize.height);
cell.questionLabel.frame = labelFrame;
cell.questionLabel.numberOfLines = 0;
cell.answerControl.selectedSegmentIndex = questionAtIndex.answer;
cell.answerControl.tag = indexPath.item;
[self.cellHeightList insertObject:[NSNumber numberWithInt:labelSize.height] atIndex:currentIndex];
return cell;
}
return nil;
}
来自 heightForRowAtIndexPath 的代码:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger currentIndex = indexPath.item;
return [[self.cellHeightList objectAtIndex:currentIndex] integerValue];
}
谢谢你!