Iphone - when to calculate heightForRowAtIndexPath for a tableview when each cell height is dynamic?

前端 未结 10 1302
迷失自我
迷失自我 2020-11-30 19:50

I have seen this question asked many times but astoundingly, I have not seen a consistent answer, so I will give it a try myself:

If you have a tableview containing

10条回答
  •  萌比男神i
    2020-11-30 20:11

    Here is what I do in very simple case, a cell containing a note held in a label. The note itself is constrained to a maximum length I am imposing, so I use a multi-line UILabel and I compute dynamically the correct eight for each cell as shown in the following example. You can deal with an UITextView pretty much the same.

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *CellIdentifier = @"Cell";
    
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
        }
    
        // Configure the cell...
        Note *note = (Note *) [fetchedResultsController objectAtIndexPath:indexPath];
        cell.textLabel.text = note.text;
        cell.textLabel.numberOfLines = 0; // no limits
    
        DateTimeHelper *dateTimeHelper = [DateTimeHelper sharedDateTimeHelper];
        cell.detailTextLabel.text = [dateTimeHelper mediumStringForDate:note.date];
    
        cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
    
    
        return cell;
    }
    
    
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
        //NSLog(@"heightForRowAtIndexPath: Section %d Row %d", indexPath.section, indexPath.row);
        UITableViewCell *cell = [self tableView: self.tableView cellForRowAtIndexPath: indexPath];
        NSString *note = cell.textLabel.text;
        UIFont *font = [UIFont fontWithName:@"Helvetica" size:14.0];
        CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
        CGSize bounds = [note sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
        return (CGFloat) cell.bounds.size.height + bounds.height;
    
    }
    

提交回复
热议问题