UITableViewCell,具有dynamic高度的UITextView

我需要制作一个拥有大量文本的UITableViewCell 。 我知道我可以添加一个UITextView到我的单元格,但每个条目将不会有相同数量的文本。

我知道我可以控制UITableViewCell的高度: -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath ,但那不是我正在寻找的。

情况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的高度。 例如:

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

这是相当复杂的东西,因为它涉及诸如文本视图的contentInset,在计算文本大小时您将不得不考虑这些内容。 我写了我的学习和解决scheme, 基于我的博客上的内部UITextView计算UITableViewCell高度 。 该post包含适用于通用应用程序的代码,包括表格视图样式和自动旋转。

该解决scheme非常简单,应该从iOS 7开始工作。确保StoryBoard中的UITableViewCell中的UITextViewScrolling Enabled选项已closures

然后在你的UITableViewController的viewDidLoad()中设置tableView.rowHeight = UITableViewAutomaticDimensiontableView.estimatedRowHeight > 0如:

 override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 44.0 } 

而已。 UITableViewCell的高度将根据内部UITextView的高度自动调整。