在不配置的情况下增加单元格的高度?

Posted

技术标签:

【中文标题】在不配置的情况下增加单元格的高度?【英文标题】:Increase height of cell without configuring it? 【发布时间】:2015-10-28 06:08:48 【问题描述】:

我有UITableView,因为我有自定义单元格。该自定义单元格包含一些标签。标签的文本可以是动态的,具体取决于 Json。现在我想根据标签的内容高度来制作单元格的高度,所以我使用了heightForRowAtINdexPath的方法。现在我得到了这样的单元格。

if(!self.customCell)
    
        self.customCell = [self.table_view dequeueReusableCellWithIdentifier:@"homeCell"];
    

标签可以是多行的,具体取决于数据。因此,如果我在 heightForRowAtIndexPath 中编写 cellForRowAtiNdexPath 的相同代码,那么我会得到更多的高度。但如果我不编写相同的代码,那么我得到的高度会更少标签。 截至目前,我已经为heightForRowAtIndexPath编写了以下代码。

-   (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

    CGFloat height;
      float like_height,c_one_height,c_two_height,c_three_height,tv_height,header_height,operations_height,img_like_icon_height,img_comment_icon_height,header_margin=5,tv_container_margin=5,operations_margin=5,like_top_margin=11,first_comment=10,second_comment=5,third_comment=5;
    //define variables here
    if(!self.customCell)
    
        self.customCell = [self.table_view dequeueReusableCellWithIdentifier:@"homeCell"];
    
    Post *user_post=[arr_post objectAtIndex:indexPath.row];
    int like_count=[user_post.like_count intValue];
    float comment_count=[user_post.comment_count intValue];
    if (self.customCell.beizer_image != nil)

    
        NSLog(@"inside cell beizer");

        [self.customCell.beizer_image removeFromSuperview];

        self.customCell.beizer_image=nil;

        self.customCell.tv_post.textContainer.exclusionPaths=NULL;

        self.customCell.beizer_path=nil;

    
    [self.customCell setSelectionStyle:UITableViewCellSelectionStyleNone];
    self.customCell.tv_post.text=user_post.post_description;
    self.customCell.tv_post.font = [UIFont fontWithName:user_post.font_family size:[user_post.font_size floatValue]];
    [self.customCell.tv_post setTextColor:[self colorFromHexString:user_post.font_color]];
    if([user_post.post_image isEqualToString:@"none"] && [user_post.post_video isEqualToString:@"none"])
    

        NSLog(@"NOT INSIDE THE CONDITION");

    
    else
    
        NSLog(@"INSIDE BEIZER PATH CONDITION");
        self.customCell.beizer_path = [UIBezierPath bezierPathWithRect:CGRectMake(5, 5, 100, 100)];
        self.customCell.tv_post.textContainer.exclusionPaths = @[self.customCell.beizer_path];
        self.customCell.beizer_image =[[UIImageView alloc]initWithFrame:CGRectMake(5, 5, 100, 100)];

        if(![user_post.post_image isEqualToString:@"none"])
        
            [self.customCell.beizer_image setImageWithURL:[NSURL URLWithString:[IMAGE_BASE_URL stringByAppendingString:user_post.post_image]]placeholderImage:[UIImage imageNamed:@"post_placeholder.png"]];

        
        if(![user_post.post_video isEqualToString:@"none"])
        
            [self.customCell.beizer_image setImageWithURL:[NSURL URLWithString:[IMAGE_BASE_URL stringByAppendingString:user_post.post_video_thumbnail]]placeholderImage:[UIImage imageNamed:@"post_placeholder.png"]];

        
        [self.customCell.tv_post addSubview:self.customCell.beizer_image];
    
    //make textview height dynamic
    self.customCell.tv_post.scrollEnabled=NO;
    if([user_post.post_image isEqualToString:@"none"] && [user_post.post_video isEqualToString:@"none"])
    
        CGFloat fixedWidth = self.customCell.tv_post.frame.size.width;
        CGSize newSize = [self.customCell.tv_post sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
        CGRect newFrame = self.customCell.tv_post.frame;
        newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
        self.customCell.tv_post.frame = newFrame;
        self.customCell.tv_height.constant=self.customCell.tv_post.frame.size.height;
        [self.customCell.view_tvContainer layoutIfNeeded];
    
    else
    
        CGFloat fixedWidth = self.customCell.tv_post.frame.size.width;
        CGSize newSize = [self.customCell.tv_post sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
        CGRect newFrame = self.customCell.tv_post.frame;
        newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth),fmax(self.customCell.beizer_image.frame.size.height+10,newSize.height));
        self.customCell.tv_post.frame = newFrame;
        self.customCell.tv_height.constant=self.customCell.tv_post.frame.size.height;
        [self.customCell.view_tvContainer layoutIfNeeded];
    

//    self.customCell.f_comment_top.constant=-2100;
//    [self.customCell layoutIfNeeded];
    if(like_count>0)
    
        like_height=self.customCell.label_like_count.frame.size.height;
    
    else
    
        like_height=0;
        img_like_icon_height=0;
    
    if(comment_count<=0)
    
        c_one_height=0;
        c_two_height=0;
        c_three_height=0;
        img_comment_icon_height=0;
    
    else if(comment_count==1)
    

        if(like_count<=0)
        
            self.view.translatesAutoresizingMaskIntoConstraints = NO;
            self.customCell.f_comment_top.constant=-21;
            [self.customCell layoutIfNeeded];
        
        c_one_height=self.customCell.first_comment.frame.size.height;
        c_two_height=0;
        c_three_height=0;

    
    else if(comment_count==2)
    
        if(like_count<=0)
        
            self.view.translatesAutoresizingMaskIntoConstraints = NO;
            self.customCell.f_comment_top.constant=-21;
            [self.customCell layoutIfNeeded];
        
        c_one_height=self.customCell.first_comment.frame.size.height;
        c_two_height=self.customCell.second_cmment.frame.size.height+15;
        c_three_height=0;
    
    else if(comment_count==3)
    
        if(like_count<=0)
        
//            self.customCell.f_comment_top.constant=1020;
//            [self.customCell.first_comment layoutIfNeeded];
        
        else
        

        
        c_one_height=self.customCell.first_comment.frame.size.height;
        c_two_height=self.customCell.second_cmment.frame.size.height;
        c_three_height=self.customCell.third_comment.frame.size.height+15;
    
    tv_height=self.customCell.view_tvContainer.frame.size.height;
    header_height=self.customCell.header_view_height.frame.size.height;
    operations_height=self.customCell.view_operations_height.frame.size.height;
    height = like_height+c_one_height+c_two_height+c_three_height+tv_height+operations_height+header_height;
    CGFloat margin_height=header_margin+operations_margin+tv_container_margin+like_top_margin+first_comment+second_comment+third_comment+img_comment_icon_height+img_like_icon_height;
    NSLog(@"like label height is %f",like_height);
    NSLog(@"first comment height is %f",c_one_height);
    NSLog(@"second comment height is %f",c_two_height);
    NSLog(@"third comment height is %f",c_three_height);
    NSLog(@"all margin  height is %f",margin_height);
    NSLog(@"height is %f",height);

    // Padding of 1 point (cell separator)
    height=height+margin_height;
    CGFloat separatorHeight = 1;
    return height;


我见过很多例子,其中写到配置单元格cellForRowAtIndexPath的代码写在heightForRowAtIndexPath中。

    为什么我需要重复cellForRowAtIndexPath 的代码 heightForRowAtIndexPath?

【问题讨论】:

【参考方案1】:

为什么我需要在 heightForRowAtIndexPath 中重复 cellForRowAtIndexPath 的代码?

因为 heightForRowAtIndexPath 总是在 cellForRowAtIndexPath 之前被调用。因此,要计算 heightForRowAtIndexPath 中的高度,您必须在 heightForRowAtIndexPath 中创建该单元格。

使用自动布局进行动态高度计算的最佳方式:- 你可以参考Link 做同样的事情。

【讨论】:

这将是一个耗时的过程,并且会降低性能。 不 .... 自动布局会像魅力一样工作......如果你知道如何使用自动布局,你应该尝试一下。【参考方案2】:

无需在heightForRowAtIndexPath 中配置您在cellForRowAtIndexPath 中声明的entire 单元格。

这是用于特定功能的两种方法。

cellForRowAtIndexPath 是一个DataSource 方法,用于在tableview 中配置您的单元格。

heightForRowAtIndexPath 是一个Delegate 方法,用于根据您计划在cellForRowAtIndexPath 中显示的内容计算tableviewcellrow 的高度。

例如,如果您正在使用UILabel 配置一个单元格(无论有多少标签)并在cellForRowAtIndexPath 中为标签分配一些文本,那么在heightForRowAtIndexPath 中,获取您分配给的文本标签,计算标签的高度并将标签的高度赋予单元格。这将根据标签的高度创建具有高度的单元格。

例如,在您的cellForRowAtIndexPath

        .....//your cell configuration code above//.....
        UILabel *lbl_myText = [[UILabel alloc]initWithFrame:CGRectZero];
        [lbl_myText setLineBreakMode:NSLineBreakByWordWrapping];
        lbl_myText.minimumScaleFactor = FONT_SIZE;
        [lbl_myText setNumberOfLines:0];
        lbl_myText.textAlignment = NSTextAlignmentRight;
        [lbl_myText setFont:[UIFont systemFontOfSize:FONT_SIZE]];

        NSString *text = [arr_text objectAtIndex:indexPath.row];
        CGSize constraint = CGSizeMake(Your_MAX_LabelWidth, Your_MAX_LabelHeight);


        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];

        paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;


        CGRect textRect = [text boundingRectWithSize:constraint
                                                 options:NSStringDrawingUsesLineFragmentOrigin
                                              attributes:@NSFontAttributeName:[UIFont systemFontOfSize:FONT_SIZE], NSParagraphStyleAttributeName: paragraphStyle.copy
                                                 context:nil];

         size = textRect.size;


         [lbl_myText setText:text];
         float widthIs = [lbl_myText.text
             boundingRectWithSize:constraint
             options:NSStringDrawingUsesLineFragmentOrigin
             attributes:@ NSFontAttributeName:lbl_myText.font 
             context:nil]
            .size.width;
         [lbl_myText setFrame:CGRectMake(X_co,Y_co,widthIs,size.height)];

heightForRowAtIndexPath:

    .....//NO cell configuration code above//.....
    NSString *cellText = [arr_text objectAtIndex:indexPath.row];

    CGSize constraint = CGSizeMake(Your_MAX_LabelWidth, Your_MAX_LabelHeight);

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];

    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;

    ////for message label
    CGRect textRect = [cellText boundingRectWithSize:constraint
                                             options:NSStringDrawingUsesLineFragmentOrigin
                                          attributes:@NSFontAttributeName:[UIFont systemFontOfSize:FONT_SIZE], NSParagraphStyleAttributeName: paragraphStyle.copy
                                             context:nil];

    CGSize labelsize = textRect.size;



    ///calculate Cell the height
    CGFloat height = MAX(labelsize.height, your_defaultcell_height);

    if(height == your_defaultcell_height)
    
       return your_defaultcell_height + 10; //10 is buffer height
    

    else
    
        return height + 10;  //10 is buffer height
    

【讨论】:

以上是关于在不配置的情况下增加单元格的高度?的主要内容,如果未能解决你的问题,请参考以下文章

在不使用单元格的情况下计算 UICollectionView 中的 sizeForItemAtIndexPath

是否可以在不刷新其他单元格的情况下刷新 ui 表视图的一部分?

如何在不丢失表格视图单元格的情况下将现有集合视图添加到表格视图

PhpSpreadsheet - 在不迭代每个单元格的情况下获取行

在不使用索引的情况下替换 pandas DataFrame 中选定单元格的值

如何在不引用其他单元格的情况下将报表从 Reporting Services 2005 导出到 Excel?