自定义 UITableView 动态单元格高度

发布于 2024-12-07 08:39:32 字数 721 浏览 0 评论 0原文

我搜索了无数博客和文章,了解如何确定自定义 UITableViewCell 的动态高度及其详细文本。我真的很难找到任何关于这方面的好的文档。

我需要做的是让单元格根据里面的文本生长,但高度永远不要低于 70。

我已经在 StackOverflow 上尝试了此类问题的几个答案,但没有一个有效。我的整个应用程序即将完成,但我确实需要在发布之前完成此任务,这很麻烦。

这是我正在尝试的,但我只是得到了一些相互重叠的单元格。根据我读到的内容,如果单元格中的自定义单元格或文本视图也需要找到框架,但我不知道如何做到这一点或将它们混合在一起以返回一个高度。

任何帮助将不胜感激,谢谢!

- (CGFloat) tableView: (UITableView *) tableView heightForRowAtIndexPath: (NSIndexPath   
*) indexPath
{

  CGSize aSize;
aSize = [[(Tweet*)[tweets objectAtIndex:indexPath.row]tweet] sizeWithFont:[UIFont 
systemFontOfSize:14]
            constrainedToSize:CGSizeMake(300.0, 1000.0)
                lineBreakMode:UILineBreakModeTailTruncation];

return  aSize.height;
}

I have search and searched through endless blogs and articles on how to determine a dynamic height for a custom UITableViewCell and its detailed text. I have really had a hard time finding any good documentation on this.

What I need to do is have the cell grow according to the the text inside but never go below a height of 70.

I have tried several of the answers for this type of question here on StackOverflow but none of them worked. My whole app is just about finished but I really need to get this accomplished before I release and its troublesome.

Here is what I am trying but I just get a slop of cells overlapping each other. From what I read I need to find the frame if the custom cell or textview in the cell as well but I am not sure how to do that or mix them all together to return one height.

Any Help would be greatly appreciated Thank you!

- (CGFloat) tableView: (UITableView *) tableView heightForRowAtIndexPath: (NSIndexPath   
*) indexPath
{

  CGSize aSize;
aSize = [[(Tweet*)[tweets objectAtIndex:indexPath.row]tweet] sizeWithFont:[UIFont 
systemFontOfSize:14]
            constrainedToSize:CGSizeMake(300.0, 1000.0)
                lineBreakMode:UILineBreakModeTailTruncation];

return  aSize.height;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

也只是曾经 2024-12-14 08:39:32

不久前我遇到了类似的问题,这对我帮助很大。

#define PADDING 10.0f
- (CGFloat)tableView:(UITableView *)t heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *text = [self.items objectAtIndex:indexPath.row];
    CGSize textSize = [text sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:CGSizeMake(self.tableView.frame.size.width - PADDING * 3, 1000.0f)];

    return textSize.height + PADDING * 3;
}

I had a similar issue a while back and this helped me tremendously.

#define PADDING 10.0f
- (CGFloat)tableView:(UITableView *)t heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *text = [self.items objectAtIndex:indexPath.row];
    CGSize textSize = [text sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:CGSizeMake(self.tableView.frame.size.width - PADDING * 3, 1000.0f)];

    return textSize.height + PADDING * 3;
}
や莫失莫忘 2024-12-14 08:39:32

嘿,所以您需要将字符串列表存储在 NSArray 中,然后您需要使用 sizeWithFont:constrainedToSize 计算 nsstring 的高度:可以在此处找到文档 http://developer.apple.com/library/ios/#documentation/UIKit/Reference/NSString_UIKit_Additions/Reference/Reference.html

所以你的 tableView 方法应该看起来像

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject:[UIFont fontWithName:"Helvetica" size:9] forKey: NSFontAttributeName];

     CGSize cell_size = [string boundingRectWithSize:CGSizeMake(300,999) 
                            options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin     
                            attributes:stringAttributes context:nil].size;
if (cell_size.height > 70)
{
return cell_size.height;
}
else 
{
return 70;
}
}

编辑:这有已更新至 iOS 7

Hey there so you are going to need to store the list of strings in an NSArray and then you are going to need to calculate the height of the nsstring using sizeWithFont:constrainedToSize: the documentation is found here http://developer.apple.com/library/ios/#documentation/UIKit/Reference/NSString_UIKit_Additions/Reference/Reference.html

so your tableView method should look something like

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject:[UIFont fontWithName:"Helvetica" size:9] forKey: NSFontAttributeName];

     CGSize cell_size = [string boundingRectWithSize:CGSizeMake(300,999) 
                            options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin     
                            attributes:stringAttributes context:nil].size;
if (cell_size.height > 70)
{
return cell_size.height;
}
else 
{
return 70;
}
}

EDIT : THIS has been updated for iOS 7

双手揣兜 2024-12-14 08:39:32

我尝试了很多解决方案,但有效的解决方案是一位朋友建议的:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    int height = [StringUtils findHeightForText:yourLabel havingWidth:yourWidth andFont:[UIFont systemFontOfSize:17.0f]];

    height += [StringUtils findHeightForText:yourOtherLabel havingWidth:yourWidth andFont:[UIFont systemFontOfSize:14.0f]];

    return height + CELL_SIZE_WITHOUT_LABELS; //important to know the size of your custom cell without the height of the variable labels
}

StringUtils.h 类:

 #import <Foundation/Foundation.h>

    @interface StringUtils : NSObject

    + (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font;

    @end

StringUtils.m 类:

    #import "StringUtils.h"

    @implementation StringUtils

    + (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font {
        CGFloat result = font.pointSize+4;
        if (text) {
            CGSize size;

            CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, CGFLOAT_MAX)
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:@{NSFontAttributeName:font}
                                              context:nil];
            size = CGSizeMake(frame.size.width, frame.size.height+1);
            result = MAX(size.height, result); //At least one row
        }
        return result;
    }

    @end

它非常适合我。我有一个自定义单元格,其中包含 3 个固定大小的图像、2 个固定大小的标签和 2 个可变标签。工作起来就像一个魅力。希望它也适合你。

最好的问候,亚历山大。

I tried many solutions, but the one that worked was this, suggested by a friend:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    int height = [StringUtils findHeightForText:yourLabel havingWidth:yourWidth andFont:[UIFont systemFontOfSize:17.0f]];

    height += [StringUtils findHeightForText:yourOtherLabel havingWidth:yourWidth andFont:[UIFont systemFontOfSize:14.0f]];

    return height + CELL_SIZE_WITHOUT_LABELS; //important to know the size of your custom cell without the height of the variable labels
}

The StringUtils.h class:

 #import <Foundation/Foundation.h>

    @interface StringUtils : NSObject

    + (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font;

    @end

StringUtils.m class:

    #import "StringUtils.h"

    @implementation StringUtils

    + (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font {
        CGFloat result = font.pointSize+4;
        if (text) {
            CGSize size;

            CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, CGFLOAT_MAX)
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:@{NSFontAttributeName:font}
                                              context:nil];
            size = CGSizeMake(frame.size.width, frame.size.height+1);
            result = MAX(size.height, result); //At least one row
        }
        return result;
    }

    @end

It worked perfectly for me. I had a Custom Cell with 3 images with fixed sizes, 2 labels with fixed sizes and 2 variable labels. Worked like a charm. Hope it works for you too.

Best regards, Alexandre.

心凉怎暖 2024-12-14 08:39:32

iOS 7

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    NSString *text = @"Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello HelloHello HelloHello HelloHello HelloHello HelloHello Hello";

    CGRect rect = [text boundingRectWithSize:CGSizeMake(280.0f, CGFLOAT_MAX) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin attributes:@{
        NSFontAttributeName: [UIFont fontWithName:@"Hellvetica" size:14.0f]
    } context:nil];

    return CGSizeMake(320.0f, ceil(rect.size.height) + 10.0f);
}

iOS 7

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    NSString *text = @"Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello HelloHello HelloHello HelloHello HelloHello HelloHello Hello";

    CGRect rect = [text boundingRectWithSize:CGSizeMake(280.0f, CGFLOAT_MAX) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin attributes:@{
        NSFontAttributeName: [UIFont fontWithName:@"Hellvetica" size:14.0f]
    } context:nil];

    return CGSizeMake(320.0f, ceil(rect.size.height) + 10.0f);
}

我刚刚写了关于这个问题以及我最终决定如何解决它的文章。您可以在这里阅读:基于内容的动态 UITableView 单元格高度 基本上,我创建了一个 UITableView 子类

,它可以自动处理和计算默认单元格和自定义单元格的动态单元格高度。它不是灵丹妙药,可能需要扩展和调整,但我已经在几个应用程序中按原样使用它,并取得了良好的效果。

您可以在这里获取代码: https://github.com/danielsaidi/AutoSizeTableView

希望它有帮助!

(...如果没有,我很想听听为什么不)

I just wrote about this problem and how I finally decided to solve it. You can read about it here: Dynamic UITableView Cell Height Based on Contents

Basically, I created a UITableView subclass that automates the handling and calculation of dynamic cell height for both default and custom cells. It is not a silver bullet and probably needs to be extended and tweaked, but I have used it as is in several apps with good result.

You can grab the code here: https://github.com/danielsaidi/AutoSizeTableView

Hope it helps!

(...and if it didn't, I'd love to hear why not)

芸娘子的小脾气 2024-12-14 08:39:32

使用 UITableViewDelegate 方法:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
 // here you need to get height of your textlabel in your custom cell. 
 MyCustomCell *myCell = (MyCustomCell *)[tableView cellForRowAtIndexPath:indexPath];
 return myCell.myTextLabel.frame.size.height + 20;
}

类似这样

Use UITableViewDelegate method:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
 // here you need to get height of your textlabel in your custom cell. 
 MyCustomCell *myCell = (MyCustomCell *)[tableView cellForRowAtIndexPath:indexPath];
 return myCell.myTextLabel.frame.size.height + 20;
}

Something like this

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文