我目前正在尝试让UITableView根据数组中的文本使用自定义单元格高度 . 我看到的问题是文本似乎在点上挤压而不是填充自定义单元格的全长 . 这导致文本在单元格上重叠,有时会在单元格下消失 .
这是我用来确定单元格高度的代码,我不确定标准的UILabel文本高度,但这似乎在字体的高度I处很好 .
if (indexPath.section == 0) {
NSString *text = [[self.recipeDict objectForKey:@"Ingredients"] objectAtIndex:[indexPath row]];
CGSize constraint = CGSizeMake(320 - (10 * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
CGFloat height = size.height;
return height + 20;
}
另外,如果单元格的创建要么是对我的问题的阻碍,要么只是帮助你知道发生了什么,也就是这样 .
UITableViewCell *cell;
UITableViewCell *ingredientCell;
UITableViewCell *methodCell;
if (indexPath.section == 0) {
UILabel *ingredientText;
static NSString *ingredientCellIdentifier = @"Ingredient Cell";
ingredientCell = [tableView dequeueReusableCellWithIdentifier: ingredientCellIdentifier];
if (ingredientCell == nil)
{
ingredientCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: ingredientCellIdentifier] autorelease];
ingredientText = [[UILabel alloc] initWithFrame:CGRectMake(15, 7, 290, 44)];
[ingredientText setLineBreakMode:UILineBreakModeWordWrap];
[ingredientText setNumberOfLines:0];
[ingredientCell.contentView addSubview:ingredientText];
ingredientText.tag = 1;
[ingredientText release];
ingredientCell.contentMode = UIViewContentModeRedraw;
}
ingredientText = (UILabel*)[ingredientCell viewWithTag:1];
ingredientText.text = [[self.recipeDict objectForKey:@"Ingredients"] objectAtIndex: indexPath.row];
[ingredientText sizeToFit];
return ingredientCell;
}
这是我解决这个问题的第二次尝试,但它似乎超出了我目前的能力,所以我欢迎通过经验获得的智慧 .
更新 -
经过进一步调查后,似乎调整大小的UILabel ingredientText会导致问题 .
它开始时显示的高度与所显示的文本一样高,但是当重新标记该标签时,另一段需要更多行的文本的高度更大,它再也不会缩小 . 似乎sizeToFit方法使用可用高度优先考虑,而不是占用宽度并缩小高度 .
现在我在sizeToFit之后再次设置了宽度,这可以解决问题,但是根据标签的高度,它会导致奇数间距 .
2 回答
有几件事:
您尚未设置UILabel的字体,这意味着您要调整到未知高度
您需要设置UILabel自动调整遮罩,以便在单元格高度更改时调整大小
这是工作代码(已测试):
此问题的解决方案是单元格高度方法中常量中指定的宽度与稍后在cellForRowAtIndexPath方法中指定的单元格文本的框架不匹配 .
一旦这些相同,问题就会解决 .
不同的恒定尺寸导致报告的UILabel高度不一致且不准确 . 这导致设置了不正确的表行高度 .