【问题标题】:Change height of UITextView in cellForRowAtIndexPath在 cellForRowAtIndexPath 中更改 UITextView 的高度
【发布时间】:2013-06-18 13:28:22
【问题描述】:

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

“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;

}

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

【问题讨论】:

    标签: uitableview height uitextview


    【解决方案1】:

    我终于通过在代码中更改 UITextview 的约束来让它工作。

    我已经创建了 IBOutlet,它附加到 UITextview 的约束。

    IBOutlet NSLayoutConstraint * postContentHeightConstraint;
    

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

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

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

    [self.postContent layoutIfNeeded];
    

    【讨论】:

    • 我遇到了同样的问题。我修复它的方法是继承UITableViewCell,覆盖drawRect: 方法,并将UITextView 的高度设置为textView.contentSize.height。我已经有了 UITableViewCell 子类,但如果你只需要这样的话,你可能只是子类 UITextView
    【解决方案2】:

    在您的表视图委托中实现tableView:heightForRowAtIndexPath:

    更新:要在 UITextView 创建后更新其高度,请在设置框架后调用[cell.postIntro setNeedsLayout]

    【讨论】:

    • 这个功能已经有了。那是调整工作正常的单元格的高度。我只想更改单元格内UITextView 的高度(每个单元格不同)
    • 还是不行,只是在我向下滚动并再次备份后才改变。
    • 会不会和uitextview的自动布局和约束有关?
    【解决方案3】:

    要更改UITextView 的高度,请调用

    [tableView beginUpdates];
    [tableView endUpdates];
    

    在为 UITextView 设置新尺寸之后。

    问题thisthis 将帮助您解决问题。

    希望答案有所帮助!

    【讨论】:

      猜你喜欢
      • 2014-05-19
      • 2014-04-20
      • 1970-01-01
      • 2016-03-04
      • 2013-08-23
      • 2015-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多