我在我的应用程序中创建了自定义单元格。我想获取 HeightForRowAtIndexPath
中的每个单元格。请告诉我如何在此方法中获取自定义单元格。我已经尝试过这段代码,但是导致无限循环并最终使应用程序崩溃。
HomeCell *cell=(HomeCell *)[tableView cellForRowAtIndexPath:indexPath];
编辑:
我已经试过了,但它让我的单元格高度为零。
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"HomeCell";
HomeCell *cell = (HomeCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
float tv_view_height=cell.tv_post.frame.size.height;
float like_count_height=cell.label_like_count.frame.size.height;
float first_comment_height=cell.first_comment.frame.size.height;
float second_comment_height=cell.second_cmment.frame.size.height;
float third_comment_height=cell.third_comment.frame.size.height;
Post *user_post=[arr_post objectAtIndex:indexPath.row];
float comment_count=[user_post.comment_count intValue];
if(comment_count<=0)
{
first_comment_height=0;
second_comment_height=0;
third_comment_height=0;
}
else if(comment_count==1)
{
second_comment_height=0;
third_comment_height=0;
}
else if(comment_count==2)
{
third_comment_height=0;
}
float like_count=[user_post.like_count intValue];
if(like_count<=0)
{
like_count_height=0;
}
float total_height=tv_view_height+like_count_height+first_comment_height+second_comment_height+third_comment_height;
NSLog(@"total heigh is %f'",total_height);
return total_height;
}
请问哪种方法最好?
最佳答案
How to get cell in heightForRowAtIndexPath?
这是不可能的,因为当调用 -heightForRowAtIndexPath
时,还没有创建单元格。您需要了解 UITableView
的工作原理:
UITableView 询问它的数据源它将有多少个部分
-numberOfSectionsInTableView
此时没有创建单元格。
UITableView 询问它的数据源每个部分将有多少行
-numberOfRowsInSection
此时没有创建单元格。
UITableView 询问它是每个可见行的委托(delegate)高度,以了解单元格的位置
-heightForRowAtIndexPath
此时没有创建单元格。
UITableView 要求它的数据源给它一个单元格以显示在给定的索引路径
-cellForRowAtIndexPath
此时单元格已创建。
您可以从数据模型中计算出每个单元格的高度。您不需要单元格——您已经知道将包含评论的框架宽度,您知道它的内容,您知道它的字体,您知道换行模式等。因此,您可以计算高度。例如:
CGFloat commentsHeight = 0;
Post *user_post = [arr_post objectAtIndex:indexPath.row];
for (NSString *comment in user_post.comments)
{
CGRect commentrect = [comment boundingRectWithSize:CGSizeMake(self.view.bounds.size.width - 18, FLT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin)
attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]}
context:nil];
commentsHeight += commentrect.size.height;
}
并且您可以根据其数据模型计算单元格其他组件的高度。
但现在,在 2015 年,这不是最好的方法。你真的会更好阅读显示@Zil 的教程,并使用自动布局。
关于ios - 如何获取 heightForRowAtIndexPath 中的单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33230928/