我试图实现动态大小的 tableView 单元格。单元格有一个 UILabel(除其他外),其中包含可变数量的文本。在我自定义单元格之前,我只是使用 cell.textLabel.text 来设置文本,并且单元格调整大小并显示所有文本。我根本不必弄乱标签。但是现在我的单元格中有一个自定义的 UILabel 并且文本被切断了。我在这里查看了很多答案,但似乎没有任何效果。
这是我的代码:
//This method gets the size of the text that will be inside the cell/label. This works fine
-(CGFloat)getLabelHeightForText:(NSString *)text andWidth:(CGFloat)labelWidth
{
CGSize maximumSize = CGSizeMake(labelWidth, 10000);
UIFont *systemFont = [UIFont systemFontOfSize:15.0];
//provide appropriate font and font size
CGSize labelHeightSize = [text sizeWithFont:systemFont
constrainedToSize:maximumSize
lineBreakMode:NSLineBreakByWordWrapping];
return labelHeightSize.height;
}
//Dynamically changes the cell height. This works fine
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *reviewText = [[self.reviews objectAtIndex:indexPath.row] objectForKey:@"reviewText"];
CGFloat textHeight = [self getLabelHeightForText:reviewText andWidth:self.tableView.frame.size.width];
return (textHeight + 40);
}
//This is what doesnt seem to be working.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
//Review label
NSString *reviewText = [[self.reviews objectAtIndex:indexPath.row] objectForKey:@"reviewText"];
UILabel *reviewLabel = (UILabel *)[cell viewWithTag:102];
CGFloat reviewLabelHeight = [self getLabelHeightForText:reviewText andWidth:reviewLabel.frame.size.width];
reviewLabel.frame = CGRectMake(reviewLabel.frame.origin.x, reviewLabel.frame.origin.y, reviewLabel.frame.size.width, reviewLabelHeight);
reviewLabel.text = reviewText;
reviewLabel.numberOfLines = 0;
reviewLabel.lineBreakMode = NSLineBreakByWordWrapping;
NSLog(@"Height: %f", reviewLabel.frame.size.height);
NSLog(@"Width: %f", reviewLabel.frame.size.width);
// cell.textLabel.text = [[self.reviews objectAtIndex:indexPath.row] objectForKey:@"reviewText"];
//
// cell.textLabel.numberOfLines = 0;
//
// cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
return cell;
}
如您所见,我记录了标签的高度和宽度。宽度保持恒定 280,这是正确的,高度根据文本动态变化。一切看起来都应该可以正常工作。但遗憾的是它没有。单元格调整大小。标签(从 NSLogs 判断)似乎可以很好地调整大小,那么为什么我的文本会被截断?
谢谢