xcode 动态调整 tableView 单元格的高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8030608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
dynamically size the height of the tableView cells
提问by iDev
I am able to display the cell content in the table and also Wordwrap it to display the message entirely. But I noticed that if the content is more than the height than it becomes clumpsy. How do I increase the heighten a cell dynamically if the content is too large. Since I am retrieving data from a url the length varies so I do not want to hard code the height but want to vary it as per the content length.
我能够在表格中显示单元格内容,也可以将其自动换行以完全显示消息。但我注意到,如果内容超过高度,它就会变得结块。如果内容太大,如何动态增加单元格的高度。由于我从 url 检索数据,因此长度会有所不同,因此我不想对高度进行硬编码,但希望根据内容长度进行更改。
The code that I have tried so far is as under :
到目前为止,我尝试过的代码如下:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *person = [myPeople objectAtIndex:[indexPath row]];
NSString *personName = [person valueForKey:@"text"];
NSString *cellText = personName;
UIFont *cellFont = [UIFont fontWithName:@"Helvetica-neuve" size:21.0];
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
int buffer = 70;
return labelSize.height + buffer;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [commentView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 6;
cell.textLabel.font = [UIFont fontWithName:@"Helvetica-neuve" size:21.0];
[cell.textLabel setMinimumFontSize:13.0];
[cell.textLabel setAdjustsFontSizeToFitWidth:NO];
}
NSDictionary *person = [myPeople objectAtIndex:[indexPath row]];
NSString *personName = [person valueForKey:@"text"];
cell.textLabel.text = personName;
return cell;
}
采纳答案by Warren Burton
Much as I dislike posting just a link. This will show you how to calculate the correct height for your cell on the fly.
就像我不喜欢只发布链接一样。这将向您展示如何即时计算单元格的正确高度。