【问题标题】:heightForRowAtIndexPath being called too early过早调用 heightForRowAtIndexPath
【发布时间】:2013-05-28 10:47:52
【问题描述】:

我目前正在通过 Json 获取 Twitter 提要,并且在获取推文长度之前调用了 heightForRowAtIndexPath。因此,加载 heightForRowAtIndexPath 时 fullTweet.length 始终为零。我正在尝试像http://gyazo.com/632d09685268e1737d3c58bf1718cbff.png 这样调整单元格的大小,这样我就不会浪费任何额外的空格。

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if(fullTweet.length >= 50) {
  return 50.0f;
      } else
  return 92.0f;
}

我的方法是如何工作的

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

static NSString *CellIdentifier = @"TweetCell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *tweet = [tweets objectAtIndex:indexPath.row];

NSString *text = [tweet objectForKey:@"text"];
cell.textLabel.text = text;
fullTweet = text;
NSLog(@"%i", fullTweet.length);
cell.textLabel.numberOfLines = 3;

return cell;
}

有什么想法吗?

【问题讨论】:

    标签: objective-c uitableview twitter height cells


    【解决方案1】:

    您似乎尝试使用实例变量fullTweet 将单元格的文本从cellForRowAtIndexPath 传递到heightForRowAtIndexPath

    这是行不通的,因为heightForRowAtIndexPath 会先为所有单元格调用,然后再调用 可见单元格调用cellForRowAtIndexPath

    所以heightForRowAtIndexPath 应该从数据源获取信息, 类似:

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        NSDictionary *tweet = [tweets objectAtIndex:indexPath.row];
        NSString *text = [tweet objectForKey:@"text"];
        if ([text length] <= 50) {
            return 50.0f;
        } else {
            return 92.0f;
        }
    }
    

    【讨论】:

      【解决方案2】:

      收到数据后,只需在您的UITableView 上拨打reloadData。这将强制表格视图重新加载所有单元格。

      【讨论】:

        猜你喜欢
        • 2015-09-08
        • 2011-03-22
        • 2012-10-31
        • 2015-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多