ios 根据文本量更改 UITableViewCell 高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9827126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 17:30:04  来源:igfitidea点击:

Change the UITableViewCell Height According to Amount of Text

iosobjective-ciphoneuitableview

提问by Josh Kahane

I need to be able to adjust the height of a single cell in my UITableView so that it fits the amount of text in its detail label.

我需要能够调整 UITableView 中单个单元格的高度,使其适合其详细信息标签中的文本量。

I have played with the following but it hasn't work for me:

我玩过以下游戏,但对我不起作用:

How do I wrap text in a UITableViewCell without a custom cell

如何在没有自定义单元格的 UITableViewCell 中包装文本

Attempted code:

尝试的代码:

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];
}

and

- (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;
}

This hasn't worked, it shows the entire string on the cell, however the cell height isn't affected at all.

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

采纳答案by Nitin Alabur

Based on the code you have provided, I think you are increasing only the cell height and not the cell.textLabel's height.

根据您提供的代码,我认为您只增加了单元格高度,而不是 cell.textLabel 的高度。

Ideally, you should set the frame size of cell.textLabel and the cell for you to see the full text in the cell.

理想情况下,您应该设置 cell.textLabel 和单元格的框架大小,以便您查看单元格中的全文。

A neat way to see whats wrong with a view in terms of size, is to color it different than the background (try setting cell.textLabel background to yellow) and see if the height is actually being set.

查看视图在大小方面有什么问题的一种巧妙方法是将其着色为与背景不同的颜色(尝试将 cell.textLabel 背景设置为黄色)并查看是否实际设置了高度。

Here's how it should be

这应该是这样的

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

Hope this helps!

希望这可以帮助!

update: This is quite an old answer, and many lines in this answer may be deprecated.

更新:这是一个很旧的答案,这个答案中的许多行可能已被弃用。

回答by stepik21

Its simple, just add this to your code:

很简单,只需将其添加到您的代码中:

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

It automatically count an height of row and than return a float... :-)

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

Hope this helps!

希望这可以帮助!

回答by AJPatel

Hi Josh,

嗨,乔希,

Using tableView:heightForRowAtIndexPath:you can give the size of each row at run time. now your problem is how to get height from your string there are function in NSString class by this code your problem,

使用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;
}

by below line you set your label`s num. of line to max. so set it in cellForRowAtIndexPath: method.

通过下面的行,您可以设置标签的编号。线到最大。所以在 cellForRowAtIndexPath: 方法中设置它。

cell.textLabel.numberOfLines = 0;

cell.textLabel.numberOfLines = 0;

if you use some custom cell then manage all label`s string with this and get sum of all that height then set the height of your cell.

如果您使用一些自定义单元格,则使用此管理所有标签的字符串并获得所有高度的总和,然后设置单元格的高度。

Edit :iOS 8 onwards if you set proper autolayout constraints to label then you have to set only following delegate method to achieve this.

编辑: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;
}

that`s it. no any calculation required. For more information check this tutorial.

就是这样。无需任何计算。有关更多信息,请查看本教程。

回答by Phan Van Linh

In your CustomCell: Remember to add the constraint top and bottomfor your UILabel

在你CustomCell:记住添加约束顶部和底部为您UILabel

For adjust UILabel height depend on text just change UILabelline to 0 (see the answer here)

要根据文本调整 UILabel 高度,只需将UILabelline更改为 0 (请参阅此处的答案)

Then in your code, just only set 2 line

然后在你的代码中,只设置 2 行

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

Here is my custom cell
enter image description hereHere is my UILabelconstraints
enter image description here
The screen you will achieve

这是我的自定义单元格
在此处输入图片说明这是我的UILabel约束条件 您将实现的屏幕
在此处输入图片说明

enter image description here

在此处输入图片说明

=== Suggestion===
IFyour cell has some UILabelsand Images(not like my example) then:

===建议===
如果你的手机有一些UILabelsImages(不像我的例子)那么:

  • You should put all UILabelsand Imagesto one GroupView(View)
  • Add the constraint top and bottom to supper viewfor this GroupView(like the UILabel in my image)
  • Adjust UILabel height like the my suggestion above
  • Adjust the GroupViewheight depend on the content (the content is all UILabelsand Images)
  • Finally, change estimateRowHeightand tableView.rowHeightlike the code above
  • 你应该把所有UILabelsImages一个GroupView(查看)
  • constraint top and bottom to supper view为此添加GroupView(如我图像中的 UILabel)
  • 像我上面的建议一样调整 UILabel 高度
  • GroupView根据内容调整高度(内容为 allUILabelsImages
  • 最后,更改estimateRowHeighttableView.rowHeight喜欢上面的代码

Hope this help

希望这有帮助

回答by Rubaiyat Jahan Mumu

For swiftdevelopers:

对于swift开发人员:

Custom cell: At first you can calculate the heightof the text like below:

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

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
    }

Set the widthof your text label

设置宽度您的文本标签

Then call this function:

然后调用这个函数:

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

        return (heightOfRow + 60.0)
}

For Basic cell:

对于基本单元格

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
           return UITableViewAutomaticDimension
    }

This function will not work for custom cells.

此功能不适用于自定义单元格

Hope it will work.

希望它会起作用。

回答by Harry P

You can write a method globally to make it so it can be used throughout the app. You need to pass the text, font and width as per your requirement.

您可以全局编写一个方法以使其可以在整个应用程序中使用。您需要根据您的要求传递文本、字体和宽度。

In Swift 4:

在 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;
}

回答by Kevin Low

In tableView:heightForRowAtIndexPath:you can take the text and use sizeWithFont:constrainedToSize:in order to get the size of the text.

tableView:heightForRowAtIndexPath:您可以获取文本并使用sizeWithFont:constrainedToSize:以获取文本的大小。

Then just return the height plus some extra spacing for buffer.

然后只需返回高度加上一些额外的缓冲区间距。

回答by VaporwareWolf

I was able to get this accomplished using autolayout. Make sure your label snaps to the top and bottom of the cell (I'm using a prototype cell), and it's lines set to 0. Then in the tableView:heightForRowAtIndexPath:sizeWithFont:constrainedToSize:you can set the height of the cell by doing the calculation on the text size:

我能够使用自动布局完成这项工作。确保您的标签对齐单元格的顶部和底部(我使用的是原型单元格),并且它的行设置为 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;

回答by HIMANSHU VARSHNEY

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;


}