uitableview – 在cellForRowAtIndexPath中更改UITextView的高度

我正在尝试更改我在tableView的自定义Cell中的UITextView的高度.

‘OverviewCell’是笔尖中此自定义单元格的标识符,并且UITextView的’postIntro’也被拖入笔尖.

可悲的是,只有在我滚动高度后才改变高度.在不滚动的情况下可见的单元格只是笔尖的默认高度.

当我尝试更改’postImage‘的高度时,会发生同样的问题.

这是我的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString *CellIdentifier = @"OverviewCell";

  OverviewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

  Post *post = [self.posts objectAtIndex:[indexPath row]];

  if(!cell)
  {
    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"OverviewCell" owner:nil options:nil];

    for(id currentObject in topLevelObjects)
    {
        if([currentObject isKindOfClass:[OverviewCell class]])
        {
            cell = (OverviewCell *)currentObject;
            break;
        }
    }
  }

  [[cell postImage] setImage:[UIImage imageWithData:post.image]];
  [[cell postTitle] setText:post.title];
  [[cell postIntro] setText:post.intro];

  // Resize the intro textview so the text fits in.
  CGRect frame = cell.postImage.frame;
  frame.size.height = 20; //cell.postIntro.contentSize.height;
  [cell.postIntro setFrame:frame];

  NSLog([NSString stringWithFormat:@"Height of textView on indexpath %i is set to %f", indexPath.row ,cell.postImage.frame.size.height]);

  return cell;

}

欢迎对我的代码提出任何其他建议……

最佳答案 我终于通过在代码中更改UITextview的约束来实现它.

我创建了和附加到UITextview约束的IBOutlet.

IBOutlet NSLayoutConstraint * postContentHeightConstraint;

之后,我将约束高度设置为单元格的指定高度(contentSize).

self.postContentHeightConstraint.constant = self.postContent.contentSize.height;

将新高度设置为约束后,调用UITextView上的layoutIfNeeded函数

[self.postContent layoutIfNeeded];
点赞