从自定义单元格加载时如何调整单元格表格的高度?

我有一个应用程序,我从3种types的自定义cells UITableViewUITableView 。 我为此做了3个自定义类,并使用布局subview方法添加了所有元素。 但问题是所有的3都有一个文本视图,它可以是可变的。在那个文本视图内容我需要添加一个button和一个label 。我可以做,但我需要增加的单元格的大小到内容视图的大小。有人能帮我实现这个吗?

请检查自定义的单元格高度将与表格视图中的每个单元格高度相同。

您可以使用以下function来调整表视图的单元格高度。

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return height; } 

你可以使用这样的代码。

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { Defination *definition = [self.dataSource objectAtIndex:indexPath.row]; NSString *detailString = definition.detailString; CGSize detailSize; detailSize = [detailString sizeWithFont:fontSize(12.0) constrainedToSize:CGSizeMake(420, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap]; return detailSize.height + 20.0; } 

生病又增加了一个测量更复杂细胞的例子。 介意我的测量代码不是100%正确的,但它显示的方法

 + (CGFloat)calculatedCellHeightForTweet:(id)tweet width:(CGFloat)width { //text CGSize s1 = [tweet[@"text"] sizeWithFont:[UIFont systemFontOfSize:[UIFont smallSystemFontSize]] constrainedToSize:CGSizeMake(width, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping]; //user NSString *text; if(![tweet[@"to_user"] isKindOfClass:[NSNull class]]) text = [NSString stringWithFormat:@"%@ > %@", tweet[@"from_user"], tweet[@"to_user"]]; else text = tweet[@"from_user"]; CGSize s2 = [text sizeWithFont:[UIFont boldSystemFontOfSize:[UIFont labelFontSize]] forWidth:width lineBreakMode:NSLineBreakByWordWrapping]; return fmaxf(s1.height + s2.height + /*padding*/ 44, 60); } 

你可以使用下面的函数来计算高度

 -(CGSize)SizeOfString:(NSString *)string withFont:(UIFont *)font constrainedToWidth:(CGFloat)width { CGSize size = [string sizeWithFont:font constrainedToSize:CGSizeMake(width, 4000) lineBreakMode:UILineBreakModeWordWrap]; return CGSizeMake(width, size.height + 10); } 

呼叫

 CGSize size = [self SizeOfString:your_text withFont:your_font constrainedToWidth:width_of_showing_area];