How to resize UITableViewCell to fit its content?

前端 未结 8 770
有刺的猬
有刺的猬 2020-12-08 05:34

I have a UITableview with multiple reusable TableViewCells. In one cell I have a UITextView, that resizes itself to fit its content. Now I \"just\

8条回答
  •  余生分开走
    2020-12-08 05:40

    I favor this solution of Jure

    • First, set constraints of textview to be pinned with its superview (cell's contentView in this case).
    • Disable textView.scrollEnabled
    • Set

      table.rowHeight = UITableViewAutomaticDimension;
      tableView.estimatedRowHeight = 44;
      

      If finally, your code not works, then use this instead

      - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
          return UITableViewAutomaticDimension;
      }
      
      - (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
          return 44;
      }
      
    • Implement UITextViewDelegate like this:

      - (void)textViewDidChange:(UITextView *)textView {
           CGPoint currentOffset = self.tableView.contentOffset;
           [UIView setAnimationsEnabled:NO];
           [self.tableView beginUpdates];
           [self.tableView endUpdates];
           [UIView setAnimationsEnabled:YES];
           [self.tableView setContentOffset:currentOffset animated:NO];
        }
      

提交回复
热议问题