UITableViewCell, UITextView 动态高度 [英] UITableViewCell, UITextView with dynamic height
问题描述
我需要制作一个包含大量文本的 UITableViewCell
.我知道我可以将 UITextView
添加到我的单元格中,但每个条目的文本量不会相同.
I need to make a UITableViewCell
that holds alot of text. I know I can add a UITextView
to my cell, but each entry will not have the same amount of text.
我知道我可以控制 UITableViewCell
的高度:-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
,但就是这样不是我真正想要的.
I know I can control the height of the UITableViewCell
with: -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
, but thats not really what I am looking for.
场景 1:
---------------
| First Cell |
---------------
---------------
| Second Cell |
| with some |
| text. |
---------------
---------------
| Third Cell |
---------------
场景 2:
---------------
| First Cell |
---------------
---------------
| Second Cell |
| with some |
| more text and |
| an unknown |
| cell height. |
---------------
---------------
| Third Cell |
---------------
推荐答案
使用 UILabel
作为您的单元格文本.然后您可以使用 sizeWithFont:constrainedToSize:
来计算每个单元格内 UILabel 的高度.例如:
Use UILabel
for your cell text. You can then use sizeWithFont:constrainedToSize:
to calculate the height of that UILabel within each cell. For example:
#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;
}
这篇关于UITableViewCell, UITextView 动态高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!