Uitableview 更改cellForRowAtIndexPath中UITextView的高度

Uitableview 更改cellForRowAtIndexPath中UITextView的高度,uitableview,height,uitextview,Uitableview,Height,Uitextview,我正在尝试更改UITextView的高度,该视图位于为tableView定制的单元格中 “OverviewCell”是nib中此自定义单元格的标识符,UITextView“postIntro”也被拖到nib中 可悲的是,高度没有改变,只是在我滚动之后,高度才改变。无需滚动即可看到的单元格仅为距笔尖的默认高度 当我尝试更改“postImage”的高度时,同样的问题也会发生 这是我的代码: - (UITableViewCell *)tableView:(UITableView *)tableView

我正在尝试更改UITextView的高度,该视图位于为tableView定制的单元格中

“OverviewCell”是nib中此自定义单元格的标识符,UITextView“postIntro”也被拖到nib中

可悲的是,高度没有改变,只是在我滚动之后,高度才改变。无需滚动即可看到的单元格仅为距笔尖的默认高度

当我尝试更改“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后更新其高度,请在设置帧后调用
[cell.postIntro setNeedsLayout]
更改
UITextView的高度,请调用

[tableView beginUpdates];
[tableView endUpdates];
为UITextView设置新尺寸后

问题,并将有助于解决您的问题


希望答案有帮助

通过在代码中更改UITextview的约束,我最终实现了它

我已经创建了一个附加到UITextview约束的IBOutlet

IBOutlet NSLayoutConstraint * postContentHeightConstraint;
之后,我将约束高度设置为单元格的指定高度(
contentSize

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

[self.postContent layoutIfNeeded];

此功能已经存在。这就是调整工作正常的电池的高度。我只想更改单元格内
UITextView
的高度(每个单元格中的高度不同),但仍然不起作用,只是在向下滚动并再次向上滚动后才更改。是否可能与UITextView的自动布局和约束有关?我也有同样的问题。我修复它的方法是子类化
UITableViewCell
,重写
drawRect:
方法,并将
UITextView
的高度设置为
textView.contentSize.height
。我已经有了
UITableViewCell
子类,但是如果您只需要子类
UITextView
,就可以了。
[self.postContent layoutIfNeeded];