Is there any way refresh cell's height without reload/reloadRow?

前端 未结 4 1072
忘掉有多难
忘掉有多难 2021-01-31 09:41

I make a view like imessage, just input text into the bottom text view. I use table view to do this, and the text view in the last cell. when I input long text that more than on

4条回答
  •  南方客
    南方客 (楼主)
    2021-01-31 10:08

    The cells will resize smoothly when you call beginUpdates and endUpdates. After those calls the tableView will send tableView:heightForRowAtIndexPath: for all the cells in the table, when the tableView got all the heights for all the cells it will animate the resizing.

    And you can update cells without reloading them by setting the properties of the cell directly. There is no need to involve the tableView and tableView:cellForRowAtIndexPath:

    To resize the cells you would use code similar to this

    - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
        NSString *newText = [textView.text stringByReplacingCharactersInRange:range withString:text];
        CGSize size = // calculate size of new text
        if ((NSInteger)size.height != (NSInteger)[self tableView:nil heightForRowAtIndexPath:nil]) {
            // if new size is different to old size resize cells. 
            // since beginUpdate/endUpdates calls tableView:heightForRowAtIndexPath: for all cells in the table this should only be done when really necessary.
            [self.tableView beginUpdates];
            [self.tableView endUpdates];
        }
        return YES;
    }
    

    to change the content of a cell without reloading I use something like this:

    - (void)configureCell:(FancyCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
        MyFancyObject *object = ...
        cell.textView.text = object.text;
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        FancyCell *cell = (FancyCell *)[tableView dequeueReusableCellWithIdentifier:@"CellWithTextView"];
        [self configureCell:cell forRowAtIndexPath:indexPath];
        return cell;
    }
    
    // whenever you want to change the cell content use something like this:
    
        NSIndexPath *indexPath = ...
        FancyCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        [self configureCell:cell forRowAtIndexPath:indexPath];
    

提交回复
热议问题