如何调整大小UITableViewCell有多少文本我有? [英] How can i resize UITableViewCell for how much text that i have?

查看:114
本文介绍了如何调整大小UITableViewCell有多少文本我有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从服务器得到一些文本,我把它放到UILabel,它将添加到UITableViewCell,这个文本每次都可以改变,可以是微小或大或多行。我的问题是如何使这个UILabel自动适应文本(多行)和调整大小的UITableViewCell以适应UILabel?

I get some text from the server and i put it to the UILabel that it will be add to the UITableViewCell and this text change every time it can be tiny or large or with multiple line. my question is how can i make this UILabel to fit the text automatically (multiple line) and resize the UITableViewCell to fit the UILabel?

推荐答案

您可以在tableView的数据源中执行以下操作:

You can do the following in your tableView's datasource:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  // for the sake of illustration, say your model for this table is just an array of strings you wish to present.
  // it's probably more complex, but the idea is to get the string you want to present for the
  // cell at indexPath
  NSString *stringForThisCell = [self.model objectAtIndex:indexPath.row];

  // you can get fancier here, and dynamically get the font from the UITextView prototype
  // but for simplicity, just copy the font size you configured the text view with in your nib
  CGSize size = [stringForThisCell sizeWithFont:[UIFont systemFontOfSize:14.0]];

  // this is a little funky, because for it to be just right, you should format your prototype
  // cell height to be a good-looking height when your text view has a zero height.
  // the basic idea here is that the cell will get taller as the text does.
  return tableView.rowHeight + size.height;
}

然后,当配置单元格时,获取字符串和大小方法,并设置UITextView框架以匹配大小

Then, when you configure the cell, get the string and the size the same way, and set the UITextView frame to match the size

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {


      NSString *stringForThisCell = [self.model objectAtIndex:indexPath.row];
      CGSize size = [stringForThisCell sizeWithFont:[UIFont systemFontOfSize:14.0]];
      UITextView *myTextView = (UITextView *)[cell viewWithTag:kMY_TEXT_VIEW_TAG];  // make this tag match a tag you give the text view in the prototype cell

      myTextView.frame = CGRectMake(myTextView.frame.origin.x, myTextView.frame.origin.y, size.width, size.height);
      // the rest of your configure cell
}

这篇关于如何调整大小UITableViewCell有多少文本我有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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