Ios 如何根据文本长度动态更改文本视图高度和单元格高度,而无需滚动

Ios 如何根据文本长度动态更改文本视图高度和单元格高度,而无需滚动,ios,objective-c,uitableview,dynamic,uitextview,Ios,Objective C,Uitableview,Dynamic,Uitextview,这是我在表中显示数据的代码,我的完整数据没有显示在单元格中。 第一张图片是当我将可滚动设置为否时,第二张图片是当我不设置可滚动时。我是一个初学者。请帮我解决这个问题 您可以通过自适应布局来实现这一点。否则,您可以通过计算文本适合的高度来设置动态tableView单元格高度 您可以使用下面的方法计算文本的高度。传递文本、文本视图所需的字体和宽度 -(CGFloat)heightForText:(NSString*)text withFont:(UIFont *)font andWidth:(CGF

这是我在表中显示数据的代码,我的完整数据没有显示在单元格中。 第一张图片是当我将可滚动设置为否时,第二张图片是当我不设置可滚动时。我是一个初学者。请帮我解决这个问题


您可以通过自适应布局来实现这一点。否则,您可以通过计算文本适合的高度来设置动态tableView单元格高度

您可以使用下面的方法计算文本的高度。传递文本、文本视图所需的字体和宽度

-(CGFloat)heightForText:(NSString*)text withFont:(UIFont *)font andWidth:(CGFloat)width
{
   CGSize constrainedSize = CGSizeMake(width, MAXFLOAT);
   NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,nil];
   NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:text attributes:attributesDictionary];
   CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
   if (requiredHeight.size.width > width) {
    requiredHeight = CGRectMake(0,0,width, requiredHeight.size.height);
   }
   return requiredHeight.size.height;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return [self heightForText:@"your text view text for this row" withFont:[UIFont fontWithName:@"Helvetica" size:16] andWidth:320];
}

您可以通过自适应布局来实现这一点。否则,您可以通过计算文本适合的高度来设置动态tableView单元格高度

您可以使用下面的方法计算文本的高度。传递文本、文本视图所需的字体和宽度

-(CGFloat)heightForText:(NSString*)text withFont:(UIFont *)font andWidth:(CGFloat)width
{
   CGSize constrainedSize = CGSizeMake(width, MAXFLOAT);
   NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,nil];
   NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:text attributes:attributesDictionary];
   CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
   if (requiredHeight.size.width > width) {
    requiredHeight = CGRectMake(0,0,width, requiredHeight.size.height);
   }
   return requiredHeight.size.height;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return [self heightForText:@"your text view text for this row" withFont:[UIFont fontWithName:@"Helvetica" size:16] andWidth:320];
}

我刚刚得到它,我想动态地做它,而不是使用自动布局,这是我的代码。希望将来它对任何人都有用。

我刚得到它,我想动态地做它,而不是使用自动布局,这是我的代码。希望将来它对任何人都有用。

看看这个。看看这个。downvoter能否请您给出否决投票的原因?向具有动态高度的单元格添加文本视图的绝佳解决方案。downvoter能否请您给出否决投票的原因?向具有动态高度的单元格添加文本视图的绝佳解决方案。