ios 根据文本量更改UITableView单元格高度

pod7payv  于 2022-12-27  发布在  iOS
关注(0)|答案(9)|浏览(165)

我需要能够在UITableView中调整单个单元格的高度,使其适合其详细信息标签中的文本量。
我已经玩了以下,但它没有为我工作:
How do I wrap text in a UITableViewCell without a custom cell
尝试的代码:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0];
}

以及

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellText = @"Go get some text for your cell.";
    UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:17.0];
    CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
    CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];

    return labelSize.height + 20;
}

这并不起作用,它显示了单元格上的整个字符串,但单元格高度完全不受影响。

0sgqnhkj

0sgqnhkj1#

这很简单,只需将以下代码添加到代码中:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}

它自动计算行的高度,然后返回一个浮点数.

nlejzf6q

nlejzf6q2#

嗨乔希,
使用tableView:heightForRowAtIndexPath:,您可以在运行时给出每行的大小。现在您的问题是如何从字符串中获取高度,NSString类中的函数通过此代码解决您的问题,

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
  NSString *str = [dataSourceArray objectAtIndex:indexPath.row];
    CGSize size = [str sizeWithFont:[UIFont fontWithName:@"Helvetica" size:17] constrainedToSize:CGSizeMake(280, 999) lineBreakMode:NSLineBreakByWordWrapping];
    NSLog(@"%f",size.height);
    return size.height + 10;
}

通过下面的行,您可以将标签的行数设置为最大值。因此,请在cellForRowAtIndexPath中设置它:方法。
单元格文本标签行数= 0;
如果你使用一些自定义单元格,然后用这个来管理所有标签字符串,并得到所有高度的总和,然后设置单元格的高度。

    • 编辑:**iOS 8以上版本如果您为标签设置了适当的自动布局约束,则只需设置以下委托方法即可实现此目的。
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
   //minimum size of your cell, it should be single line of label if you are not clear min. then return UITableViewAutomaticDimension;    
   return UITableViewAutomaticDimension; 
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}

就是这样,不需要任何计算。有关详细信息,请查看tutorial.

omvjsjqw

omvjsjqw3#

CustomCell中:请记住为UILabel添加**约束top和bottom
要根据文本调整UILabel高度,只需将UILabel行更改为0(see the answer here)
然后在你的代码中,只设置2行

self.tableView.estimatedRowHeight = 80;
self.tableView.rowHeight = UITableViewAutomaticDimension;

这是我的自定义单元格


下面是我的UILabel约束

您将实现的屏幕

===建议==

    • 如果**你的单元格有一些UILabelsImages(不像我的例子),那么:
  • 您应该将所有UILabelsImages放在一个GroupView中(视图)
  • 为这个GroupView添加constraint top and bottom to supper view(就像我的图片中的UILabel)
  • 调整UILabel高度像我上面的建议
  • 根据内容调整GroupView高度(内容全部为UILabelsImages
  • 最后,按照上面的代码更改estimateRowHeighttableView.rowHeight

希望这能有所帮助

cdmah0mi

cdmah0mi4#

根据您提供的代码,我认为您只是增加了单元格高度,而没有增加cell.textLabel的高度。
理想情况下,您应该设置cell.textLabel和单元格的框架大小,以便查看单元格中的完整文本。
查看视图在大小方面的问题的一个简洁的方法是将其颜色与背景颜色不同(尝试将cell.textLabel背景设置为黄色),然后查看是否实际设置了高度。
事情应该是这样的

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0];

    NSString *cellText = @"Go get some text for your cell.";
    UIFont *cellFont = cell.textLabel.font;
    CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
    CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
    cell.textlabel.frame.size = labelSize; 
    cell.text = cellText;
}

希望这有帮助!
update:这是一个很老的答案,其中的许多行可能已经过时。

uemypmqf

uemypmqf5#

对于swift开发人员:

自定义单元格:首先,您可以计算文本的高度,如下所示:

func calculateHeight(inString:String) -> CGFloat
    {
        let messageString = inString
        let attributes : [String : Any] = [NSFontAttributeName : UIFont.systemFont(ofSize: 15.0)]

        let attributedString : NSAttributedString = NSAttributedString(string: messageString, attributes: attributes)

        let rect : CGRect = attributedString.boundingRect(with: CGSize(width: 222.0, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil)

        let requredSize:CGRect = rect
        return requredSize.height
    }

设置文本标签的**宽度
然后调用此函数:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        heightOfRow = self.calculateHeight(inString: conversations[indexPath.row].description)

        return (heightOfRow + 60.0)
}

对于基本单元格

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
           return UITableViewAutomaticDimension
    }
  • 此函数不适用于自定义单元格 *。

希望它能起作用。

idv4meu8

idv4meu86#

tableView:heightForRowAtIndexPath:中,您可以获取文本并使用sizeWithFont:constrainedToSize:来获取文本的大小。
然后只返回高度加上一些额外的缓冲区间距。

lnvxswe2

lnvxswe27#

你可以写一个全局的方法,使它可以在整个应用程序中使用。你需要根据你的要求传递文本,字体和宽度。
在Swift 4中:

func heightForText(text: String,Font: UIFont,Width: CGFloat) -> CGFloat{

    let constrainedSize = CGSize.init(width:Width, height: CGFloat(MAXFLOAT))

    let attributesDictionary = NSDictionary.init(object: Font, forKey:NSAttributedStringKey.font as NSCopying)

    let mutablestring = NSAttributedString.init(string: text, attributes: attributesDictionary as? [NSAttributedStringKey : Any])

    var requiredHeight = mutablestring.boundingRect(with:constrainedSize, options: NSStringDrawingOptions.usesFontLeading.union(NSStringDrawingOptions.usesLineFragmentOrigin), context: nil)

    if requiredHeight.size.width > Width {
        requiredHeight = CGRect.init(x: 0, y: 0, width: Width, height: requiredHeight.height)

    }
    return requiredHeight.size.height;
}
3lxsmp7m

3lxsmp7m8#

我可以使用自动布局来完成这个任务。确保你的标签对齐单元格的顶部和底部(我使用的是原型单元格),并且它的行数设置为0。然后在tableView:heightForRowAtIndexPath:sizeWithFont:constrainedToSize:中,你可以通过计算文本大小来设置单元格的高度:

NSString *key = self.detailContent.allKeys[indexPath.row];
NSDictionary *dictionary = self.detailContent[key];
NSString *cellText = dictionary[kSMDetailTableViewCellTextKey];
UIFont *cellFont = [UIFont fontWithName:kFontKeyEmondsans size:12.0];
CGSize constraintSize = CGSizeMake(252.0f, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
return labelSize.height;// + 10;
4nkexdtk

4nkexdtk9#

NSString *str;
NSArray* dictArr;

if (_index==0) {
    dictArr = mustangCarDetailDictArr[indexPath.section];

}

NSDictionary* dict = dictArr[indexPath.row];

if (indexPath.section ==0)
{

    str = [dict valueForKey:@"FeatureName"];
    if ([[dict valueForKey:@"FeatureDetail"] isKindOfClass:[NSString class]])
    {

        str = [dict valueForKey:@"FeatureDetail"];


    }
    else
    {
        if (dictArr.count>indexPath.row+1)
        {
            NSDictionary* dict2 = dictArr[indexPath.row+1];
            if ([[dict2 valueForKey:@"FeatureDetail"] isKindOfClass:[NSString class]])
            {

            }
        }

    }

}
CGSize size = [str sizeWithFont:[UIFont fontWithName:@"Helvetica" size:17] constrainedToSize:CGSizeMake(280, 999) lineBreakMode:NSLineBreakByWordWrapping];
NSLog(@"%f",size.height);
return size.height + 20;

}

相关问题