更新时间:2023-09-24 21:20:46
这里有一个更简单的方法,它对我有用:
Here is a simpler way, and it works for me:
在您的 cellForRowAtIndexPath:
函数中.第一次创建单元格:
Inside your cellForRowAtIndexPath:
function. The first time you create your cell:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0];
}
您会注意到我将标签的行数设置为 0.这使它可以根据需要使用尽可能多的行.
You'll notice that I set the number of lines for the label to 0. This lets it use as many lines as it needs.
下一部分是指定你的 UITableViewCell
有多大,所以在你的 heightForRowAtIndexPath
函数中这样做:
The next part is to specify how large your UITableViewCell
will be, so do that in your heightForRowAtIndexPath
function:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellText = @"Go get some text for your cell.";
UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:17.0];
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
return labelSize.height + 20;
}
我在返回的单元格高度上加了 20,因为我喜欢在文本周围留一点缓冲区.
I added 20 to my returned cell height because I like a little buffer around my text.