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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/129502/
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 15:16:45  来源:igfitidea点击:

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

iosobjective-ccocoa-touchuikitiphone-sdk-2

提问by Airsource Ltd

This is on iPhone 0S 2.0. Answers for 2.1 are fine too, though I am unaware of any differences regarding tables.

这是在 iPhone 0S 2.0 上。2.1 的答案也很好,但我不知道有关表格的任何差异。

It feels like it should be possible to get text to wrap without creating a custom cell, since a UITableViewCellcontains a UILabelby default. I know I can make it work if I create a custom cell, but that's not what I'm trying to achieve - I want to understand why my current approach doesn't work.

感觉应该可以在不创建自定义单元格的情况下让文本换行,因为默认情况下aUITableViewCell包含 a UILabel。我知道如果我创建一个自定义单元格,我可以让它工作,但这不是我想要实现的 - 我想了解为什么我当前的方法不起作用。

I've figured out that the label is created on demand (since the cell supports text and image access, so it doesn't create the data view until necessary), so if I do something like this:

我发现标签是按需创建的(因为单元格支持文本和图像访问,所以它在必要时才创建数据视图),所以如果我做这样的事情:

cell.text = @""; // create the label
UILabel* label = (UILabel*)[[cell.contentView subviews] objectAtIndex:0];

then I get a valid label, but setting numberOfLineson that (and lineBreakMode) doesn't work - I still get single line text. There is plenty of height in the UILabelfor the text to display - I'm just returning a large value for the height in heightForRowAtIndexPath.

然后我得到了一个有效的标签,但是设置numberOfLines它(和 lineBreakMode)不起作用 - 我仍然得到单行文本。UILabel要显示的文本中有足够的高度- 我只是为heightForRowAtIndexPath.

回答by Tim Rupe

Here is a simpler way, and it works for me:

这是一种更简单的方法,它对我有用:

Inside your cellForRowAtIndexPath:function. The first time you create your cell:

在你的cellForRowAtIndexPath:函数里面。第一次创建单元格时:

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

You'll notice that I set the number of lines for the label to 0. This lets it use as many lines as it needs.

您会注意到我将标签的行数设置为 0。这使它可以根据需要使用尽可能多的行。

The next part is to specify how large your UITableViewCellwill be, so do that in your heightForRowAtIndexPathfunction:

下一部分是指定您UITableViewCell将有多大,因此在您的heightForRowAtIndexPath函数中执行此操作:

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

I added 20 to my returned cell height because I like a little buffer around my text.

我在返回的单元格高度上加了 20,因为我喜欢在文本周围留一点缓冲区。

回答by ddiego

Updated Tim Rupe's answer for iOS7:

更新了 Tim Rupe 对 iOS7 的回答:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
    cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
    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];

    NSAttributedString *attributedText =
        [[NSAttributedString alloc]
            initWithString:cellText
            attributes:@
            {
                NSFontAttributeName: cellFont
            }];
    CGRect rect = [attributedText boundingRectWithSize:CGSizeMake(tableView.bounds.size.width, CGFLOAT_MAX)
                                               options:NSStringDrawingUsesLineFragmentOrigin
                                               context:nil];
    return rect.size.height + 20;
}

回答by Richard Le Mesurier

A brief comment / answer to record my experience when I had the same problem. Despite using the code examples, the table view cell height was adjusting, but the label inside the cell was still not adjusting correctly - solution was that I was loading my cell from a custom NIB file, which happens afterthe cell height in adjusted.

一个简短的评论/答案,记录我遇到同样问题时的经历。尽管使用的代码示例,表视图单元高度为调整,但在细胞内的标签仍然没有正确地调整-溶液,我是从一个自定义的NIB文件,这恰好装入我的手机后,在调整单元格的高度。

And I had my settings inside the NIB file to not wrap text, and only have 1 line for the label; the NIB file settings were overriding the settings I adjusted inside the code.

我在 NIB 文件中设置了不换行文本,标签只有 1 行;NIB 文件设置覆盖了我在代码中调整的设置。

The lesson I took was to make sure to always bear in mind what the state of the objects are at each point in time - they might not have been created yet! ... hth someone down the line.

我吸取的教训是确保始终牢记对象在每个时间点的状态 - 它们可能尚未创建!......有人下线。

回答by Arshad Parwez

If we are to add only text in UITableViewcell, we need only two delegates to work with (no need to add extra UILabels)

如果我们只在UITableView单元格中添加文本,我们只需要使用两个委托(无需添加额外的UILabels

1) cellForRowAtIndexPath

1) cellForRowAtIndexPath

2) heightForRowAtIndexPath

2) heightForRowAtIndexPath

This solution worked for me:-

这个解决方案对我有用:-

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{ 
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:16];
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.textLabel.numberOfLines = 0;

    [cell setSelectionStyle:UITableViewCellSelectionStyleGray]; 
    cell.textLabel.text = [mutArr objectAtIndex:indexPath.section];
    NSLog(@"%@",cell.textLabel.text);

    cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow.png" ]];

    return cell;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{  
    CGSize labelSize = CGSizeMake(200.0, 20.0);

    NSString *strTemp = [mutArr objectAtIndex:indexPath.section];

    if ([strTemp length] > 0)
        labelSize = [strTemp sizeWithFont: [UIFont boldSystemFontOfSize: 14.0] constrainedToSize: CGSizeMake(labelSize.width, 1000) lineBreakMode: UILineBreakModeWordWrap];

    return (labelSize.height + 10);
}

Here the string mutArris a mutable array from which i am getting my data.

这里的字符串mutArr是一个可变数组,我从中获取数据。

EDIT :-Here is the array which I took.

编辑:-这是我拿的数组。

mutArr= [[NSMutableArray alloc] init];

[mutArr addObject:@"HEMAN"];
[mutArr addObject:@"SUPERMAN"];
[mutArr addObject:@"Is SUPERMAN powerful than HEMAN"];
[mutArr addObject:@"Well, if HEMAN is weaker than SUPERMAN, both are friends and we will never get to know who is more powerful than whom because they will never have a fight among them"];
[mutArr addObject:@"Where are BATMAN and SPIDERMAN"];

回答by Jason

Now the tableviews can have self-sizing cells. Set the table view up as follows

现在 tableviews 可以有自定大小的单元格。设置表格视图如下

tableView.estimatedRowHeight = 85.0 //use an appropriate estimate tableView.rowHeight = UITableViewAutomaticDimension

tableView.estimatedRowHeight = 85.0 //use an appropriate estimate tableView.rowHeight = UITableViewAutomaticDimension

Apple Reference

苹果参考

回答by iOS

Try my code in swift . This code will work for normal UILabels also.

在 swift 中尝试我的代码。此代码也适用于普通 UILabels。

extension UILabel {
    func lblFunction() {
        //You can pass here all UILabel properties like Font, colour etc....
        numberOfLines = 0
        lineBreakMode = .byWordWrapping//If you want word wraping
        lineBreakMode = .byCharWrapping//If you want character wraping
    }
}

Now call simply like this

现在就这样调用

cell.textLabel.lblFunction()//Replace your label name 

回答by Vincent

I use the following solutions.

我使用以下解决方案。

The data is provided separately in a member:

数据在成员中单独提供:

-(NSString *)getHeaderData:(int)theSection {
    ...
    return rowText;
}

The handling can be easily done in cellForRowAtIndexPath. Define the cell / define the font and assign these values to the result "cell". Note that the numberoflinesis set to "0", which means take what is needed.

处理可以很容易地完成cellForRowAtIndexPath。定义单元格/定义字体并将这些值分配给结果“单元格”。请注意,numberoflines设置为“0”,这意味着需要什么。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    UIFont *cellFont = [UIFont fontWithName:@"Verdana" size:12.0];
    cell.textLabel.text= [self getRowData:indexPath.section];
    cell.textLabel.font = cellFont;
    cell.textLabel.numberOfLines=0;
    return cell;
}

In heightForRowAtIndexPath, I calculate the heights of the wrapped text. The boding size shall be related to the width of your cell. For iPad this shall be 1024. For iPhone en iPod 320.

在 中heightForRowAtIndexPath,我计算了换行文本的高度。绑定大小应与您的单元格的宽度有关。对于 iPad,这应该是 1024。对于 iPhone 和 iPod 320。

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIFont *cellFont = [UIFont fontWithName:@"Verdana" size:12.0];
    CGSize boundingSize = CGSizeMake(1024, CGFLOAT_MAX);
    CGSize requiredSize = [[self getRowData:indexPath.section] sizeWithFont:cellFont constrainedToSize:boundingSize lineBreakMode:UILineBreakModeWordWrap];
    return requiredSize.height;    
}

回答by Manish Kr. Shukla

I found this to be quite simple and straightForward :

我发现这非常简单和直接:

[self.tableView setRowHeight:whatEvereight.0f];

for e.g. :

例如:

[self.tableView setRowHeight:80.0f];

This may or may not be the best / standard approach to do so, but it worked in my case.

这可能是也可能不是这样做的最佳/标准方法,但它在我的情况下有效。

回答by dukz

I think this is a better and shorter solution. Just format the UILabel(textLabel) of the cell to auto calculate for the height by specifying sizeToFitand everything should be fine.

我认为这是一个更好、更短的解决方案。只需格式化单元格的UILabel( textLabel) 以通过指定自动计算高度sizeToFit,一切都应该没问题。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell...
    cell.textLabel.text = @"Whatever text you want to put here is ok";
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.textLabel.numberOfLines = 0;
    [cell.textLabel sizeToFit];

    return cell;
}

回答by drewh

I don't think you can manipulate a base UITableViewCell'sprivate UILabelto do this. You could add a new UILabelto the cell yourself and use numberOfLineswith sizeToFitto size it appropriately. Something like:

我不认为你可以操纵一个基础UITableViewCell's私有UILabel来做到这一点。您可以UILabel自己向单元格中添加一个新元素并使用numberOfLineswithsizeToFit来适当调整其大小。就像是:

UILabel* label = [[UILabel alloc] initWithFrame:cell.frame];
label.numberOfLines = <...an appriate number of lines...>
label.text = <...your text...>
[label sizeToFit];
[cell addSubview:label];
[label release];