[英]Vary table view cell height based on text
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).
填充单元格的文本是不可预测的(基于API请求的结果)。 What I want to do is adjust the cell's height based on if the cell's text is too lengthy for the cell (eg the cell adds '...' to the text).
我想做的是根据单元格的文本对于单元格来说是否太长来调整单元格的高度(例如,单元格在文本中添加“ ...”)。
That way whatever the result/text and gets presented into a table view cell is always fully shown. 这样一来,无论结果/文本如何显示在表格视图单元格中,都将始终完整显示。
I would prefer not to implement the heightForRowAtIndexPath
because I would have to implement a lot of code to do so. 我宁愿不实现
heightForRowAtIndexPath
因为我必须实现很多代码。
UPDATE: 更新:
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? 您能指出我要进行演示的任何资源吗,您知道该怎么做吗?
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. 您必须实现heightForRowAtIndexPath来改变表行的高度,但是并不一定需要很多代码来计算高度。
Use NSString:sizeWithFont:constrainedToSize to calculate the cell size needed. 使用NSString:sizeWithFont:constrainedToSize来计算所需的像元大小。
//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 contains the size of the label. szCell包含标签的大小。 You'll use this size both to calculate the frame of your UILabel in your cellForRowAtIndexPath, as well as in your heightForRowAtIndexPath.
您将使用此大小来计算cellForRowAtIndexPath以及heightForRowAtIndexPath中的UILabel框架。
Use heightForRowAtIndexPath
. 使用
heightForRowAtIndexPath
。 It shouldn't be lots of extra code. 它不应该有很多额外的代码。 Just get a reference to the object you are populating your cell with, check out the length of that text value and return the height you need.
只需获得一个用于填充单元格的对象的引用,检查该文本值的长度并返回所需的高度即可。 That is exactly what that delegate method is designed for.
这正是该委托方法的目的所在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.