UITableView自动调整单元格大小时,当单元格高度差异较大时出现滚动问题

8
  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{

    let json = JSON(data: activityTableView.onlineFeedsData)[indexPath.row] // new
    if(json["topic"]["reply_count"].int > 0){
        if let cell: FeedQuestionAnswerTableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier_reply) as? FeedQuestionAnswerTableViewCell{

            cell.selectionStyle = .None
            cell.tag = indexPath.row
            cell.relatedTableView = self.activityTableView
            cell.configureFeedWithReplyCell(cell, indexPath: indexPath, rect: view.frame,key: "activityTableView")
            // Make sure the constraints have been added to this cell, since it may have just been created from scratch
            cell.layer.shouldRasterize = true
            cell.layer.rasterizationScale = UIScreen.mainScreen().scale

            return cell
        }
    }else{
        if let cell: FeedQuestionTableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as? FeedQuestionTableViewCell{

            cell.selectionStyle = .None
            cell.tag = indexPath.row
            cell.relatedTableView = self.activityTableView
            cell.configureFeedCell(cell, indexPath: indexPath, rect: view.frame)
            // Make sure the constraints have been added to this cell, since it may have just been created from scratch

            cell.layer.shouldRasterize = true
            cell.layer.rasterizationScale = UIScreen.mainScreen().scale
            return cell
        }
    }


    return UITableViewCell()
}

每个单元格的高度相差200-400,因此尝试在estimatedHeightForRowAtIndexPath中实现高度计算。由于计算问题,我无法在该方法中得到确切的估计高度,并在willDisplayCell方法中缓存高度,但滚动仍然会跳动,好像需要时间来呈现。
这个单元格就像Facebook卡片类型的布局,有大量动态数据,包括可变高度的文本和图像。有人可以帮助我吗?谢谢。

你能告诉我更多关于如何计算 tableView(_:estimatedHeightForRowAtIndexPath:) 中单元格高度的信息吗? - Jebeom Gyeong
2个回答

0
如果您能够计算每个单元格的高度,只需使用tableView(_:heightForRowAtIndexPath)而不是estimatedRowHeightAtIndexPath属性。 estimatedRowHeightAtIndexPath主要用于自适应单元格等情况。

NSMutableDictionary *cellHeightsDictionary; // 在代码中初始化 cellHeightsDictionary = @{}.mutableCopy; - Yogesh More

0

试试这个。希望能对你有所帮助。它对我很有效。实际上,它在显示之前计算单元格高度。

NSMutableDictionary *cellHeightsDictionary;

// 把这个放在viewDidLoad里

cellHeightsDictionary = @{}.mutableCopy;

// UITableview 代理方法

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
NS_AVAILABLE_IOS(7_0)
{
    NSNumber *height = [cellHeightsDictionary objectForKey:indexPath];
    if (height) return height.doubleValue;
    return UITableViewAutomaticDimension;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [cellHeightsDictionary setObject:@(cell.frame.size.height) forKey:indexPath];

}

谢谢@yogesh,我一定会尝试的,但最终我还是删除了自动布局,并使用AsyncdisplayKit基于框架编写代码来实现我的要求。 - Mukesh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接