【问题标题】:How do I gracefully handle variable-length text coming in from the network in a UITableView?如何在 UITableView 中优雅地处理来自网络的可变长度文本?
【发布时间】:2016-02-10 17:36:17
【问题描述】:

我有来自网络请求的可变长度文本显示在 UTableView 中。它们不会同时出现,所以我不知道所有文本块的长度,只知道每个文本块的长度。把它想象成 Twitter 流,但必须单独请求推文。

如何在 UITableView 中优雅地显示它?我想在它们进入时显示它们,但如果我每次都重新计算单元格高度,我会在用户的滚动位置周围扔掉一大堆,这会很烦人。

我将如何优雅地处理这个问题,也许以某种方式保持滚动偏移?

【问题讨论】:

  • 也许你需要写一些代码作为帮助的起点
  • @sage444 似乎更像是一个抽象问题,不一定要求明确的代码

标签: ios objective-c uitableview cocoa-touch uiview


【解决方案1】:

试试这段代码。

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{


    MyObject *obj = [self.dataArray objectAtIndex:indexPath.row];

    CGFloat cellHeight;
    if ([self getExpectedLabelSizeForString:obj.textValue].height/15 < 2) {
        cellHeight = 55.0;
    }
    else{
        cellHeight = 35 + ([self getExpectedLabelSizeForString:obj.textValue].height - [self getExpectedLabelSizeForString:obj.textValue].height/15);
    }
    return cellHeight;
}


- (CGSize)getExpectedLabelSizeForString:(NSString *)string{

    NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                          [UIFont fontWithName:@"Helvetica" size:15], NSFontAttributeName,
                                          nil];

    CGRect frame = [string boundingRectWithSize:CGSizeMake(208,FLT_MAX)
                                        options:NSStringDrawingUsesLineFragmentOrigin
                                     attributes:attributesDictionary
                                        context:nil];

    CGSize size = frame.size;
    return size;
}

【讨论】:

    【解决方案2】:

    如果您支持 iOS8+,您可以使用自动调整单元格大小。 设置tableView.rowHeight = UITableViewAutomaticDimension 并将顶部、左侧、右侧(或宽度)和底部约束添加到单元格的contentView。还要添加一些偏移量。 细胞会自动生长。

    【讨论】:

      猜你喜欢
      • 2016-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-26
      • 1970-01-01
      • 1970-01-01
      • 2011-08-08
      • 1970-01-01
      相关资源
      最近更新 更多