根据文本改变表格视图单元格高度 [英] Vary table view cell height based on text

查看:32
本文介绍了根据文本改变表格视图单元格高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含几个单元格的表格视图.填充单元格的文本是不可预测的(基于 API 请求的结果).我想要做的是根据单元格的文本是否太长来调整单元格的高度(例如,单元格在文本中添加...").

I have a table view with a few cells. The text that fills up the cell is unpredictable (based on the result of an API request). What I want to do is adjust the cell's height based on if the cell's text is too lengthy for the cell (e.g. the cell adds '...' to the text).

这样无论结果/文本并呈现在表格视图单元格中,总是完全显示.

That way whatever the result/text and gets presented into a table view cell is always fully shown.

我不想实现 heightForRowAtIndexPath 因为我必须实现很多代码才能这样做.

I would prefer not to implement the heightForRowAtIndexPath because I would have to implement a lot of code to do so.

更新:

当我说我有很多代码要做"时,我的意思是我实际上有很多代码来解析请求、检查条件和执行算法,而且我有很多表意见.只是将这些东西移到了另一种方法上,我要走了!

When I say "I have a lot of code to do so", I mean I literally have a lot of code parsing out requests and checking for conditions and performing algorithms and plus I have many table views. Just moved that stuff to another method and Im off to go!

你能告诉我任何演示这个的资源吗,你知道怎么做吗?

Could you point me to any resources demoing this, do you know how to do this?

推荐答案

您必须实现 heightForRowAtIndexPath 来改变表格行的高度,但不一定需要大量代码来计算高度.

You must implement heightForRowAtIndexPath to vary the height of your table rows, but there isn't necessarily alot of code needed to calculate the height.

使用 NSString:sizeWithFont:constrainedToSize 计算所需的单元格大小.

Use NSString:sizeWithFont:constrainedToSize to calculate the cell size needed.

    //szMaxCell contains the width of your table cell, and the maximum height you want to allow
// strCellContents is an NSString containing the text to display

        CGSize szMaxCell = CGSizeMake (tableView.frame.size.width - 20,999);
        UIFont *font = [UIFont systemFontOfSize:12];    // whatever font you're using to display
        CGSize szCell = [strCellContents sizeWithFont:font constrainedToSize:szMaxCell lineBreakMode:UILineBreakModeWordWrap];

szCell 包含标签的大小.您将使用此大小来计算 cellForRowAtIndexPath 和 heightForRowAtIndexPath 中 UILabel 的框架.

szCell contains the size of the label. You'll use this size both to calculate the frame of your UILabel in your cellForRowAtIndexPath, as well as in your heightForRowAtIndexPath.

这篇关于根据文本改变表格视图单元格高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆