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

我有一个应用程序,我从3种类型的自定义cells UITableViewUITableView 。 我为此制作了3个自定义类,并使用布局subview方法添加了所有元素Programmatic。 但问题是所有3都有文本视图。 它可以变化。 在该文本视图内容之后,我需要添加一个按钮和一个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); } 

您可以使用以下function计算高度

 -(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];