我有一个应用程序,其中有一个 Tableview 并且在该 tableview 的每一行上我动态创建一个自定义 tableview 单元格。
下面是相关代码。
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"flowviewTableViewCell" owner:self options:nil];
cell2 = [nib objectAtIndex:0];
return cell2;
“FlowTableViewCell”是一个 UITableViewCell。 在这个自定义单元格中,我有一个表格 View 。
我在我的自定义 tableview 单元格上显示数组中的一些数据,这些数据的长度各不相同。它不是固定的。
我可以增加自定义单元格的大小,但不能增加主表格 View 的行高,具体取决于自定义表格 View 单元格的大小。
我想根据自定义表格 View 单元格的大小动态增加主表格 View 单元格大小的高度。
通过以下代码,自定义 tableView 单元格的高度正在增加。
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *str = [arrComments objectAtIndex:indexPath.row];
CGSize size = [str sizeWithFont:[UIFont fontWithName:@"Helvetica" size:14] constrainedToSize:CGSizeMake(280, 999) lineBreakMode:NSLineBreakByWordWrapping];
NSLog(@"%f",size.height);
if (size.height<20)
{
size.height=20;
//m= size.height;
}
NSLog(@"%f",size.height);
return size.height + 30;
}
如何根据自定义 tableviewcell 的大小调整主 tableview 的行高?
在这里,我附上了一些屏幕截图以便清楚地理解。
下面是我自定义的TableViewCell:
以下是我的主要 TableView :
以下是我现在得到的输出:
您可以在上图中看到,comment2 被剪切,同一帖子的 comment3 显示在下一个帖子中。
我想要如下图所示的输出。
那么,我的问题是如何根据自定义 tableview 单元格的大小动态增加主 tableview 单元格大小的高度?
请帮助我。任何帮助将不胜感激
最佳答案
您可以使用以下方法计算标签的高度:
- (CGRect)heightOfLabel:(UILabel*)resizableLable
{
CGSize constrainedSize = CGSizeMake(resizableLable.frame.size.width , 9999);
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:@"HelveticaNeue" size:11.0], NSFontAttributeName,
nil];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"textToShow" attributes:attributesDictionary];
CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil
];
if (requiredHeight.size.width > self.resizableLable.frame.size.width) {
requiredHeight = CGRectMake(0,0, self.resizableLable.frame.size.width, requiredHeight.size.height);
}
return requiredHeight;
}
从 TableView 委托(delegate)方法调用此方法:
- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
return [self heightOfLabel:cell.textLabel];
}
关于ios - 根据自定义单元格增加主tableview行高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26210816/