UITableViewCell with dynamic height iOS

前端 未结 12 2348
日久生厌
日久生厌 2020-11-27 17:54

I have implemented TableView with CustomCell in my app,

I want dynamic height of my UITableViewCell according to text length in UITableViewCell

12条回答
  •  半阙折子戏
    2020-11-27 18:59

    I needed a dynamic table view cell height based on the amount of text to be displayed in that cell. I solved it in this way:

        - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
        {
            if (!isLoading)
            {
    
                if ([self.conditionsDataArray count]>0)
                {
                    Conditions *condition =[self.conditionsDataArray objectAtIndex:indexPath.row];
                    int height;
                    UITextView *textview = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 236, 0)];   //you can set your frame according to your need
                    textview.text  = condition.comment;
                    textview.autoresizingMask = UIViewAutoresizingFlexibleHeight;
                    [tableView addSubview:textview];
                    textview.hidden = YES;
                    height = textview.contentSize.height;
                    NSLog(@"TEXT VIEW HEIGHT %f", textview.contentSize.height);
                    [textview removeFromSuperview];
                    [textview release];
                    return height;
           }
           return 55;  //Default height, if data is in loading state
    }
    

    Notice that the Text View has been added as Subview and then made hidden, so make sure you add it as SubView otherwise it's height will not be considered.

提交回复
热议问题