swift UITableView滞后于图像

时间:2014-12-23 14:17:32

标签: ios image uitableview swift lag

我想在TableView中显示图像,所以我创建了一个自定义单元格

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

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as TableViewCell

    if let image =  UIImage(data: self.photos[indexPath.row].image) {

        if image.size.width > image.size.height {

            tableView.rowHeight = view.bounds.width *  0.71

        } else { tableView.rowHeight = view.bounds.width *  1.22

        }

        cell.cellImage.image = image
    }

我遇到了如何调整单元格高度的问题,因此对于每个单独计算的图像,我使用了ImageView的剪辑子视图。

问题是,当我开始添加照片时,表格的滚动非常滞后:( 即使我删除了单元格的高度计算,也没有任何改变。

有没有人知道如何在Swift中顺利完成它?

1 个答案:

答案 0 :(得分:4)

首先,您不应该在创建表格单元格的过程中更改行高。 UITableView的行高变化非常昂贵。您应该使用UITableViewDelegate方法tableView(heightForRowAtIndexPath:)告诉表格视图每个单元格的高度。这几乎肯定是你的主要问题。

一个较小的问题是,从数据创建UIImage有点贵,而且您不断创建新图像然后将它们丢弃。

这两者的解决方案很简单。创建所有图像并将其放入模型中。然后,tableView(cellForWRowAtIndexPath:)可以将已创建的图像分配给图像视图,tableView(heightForRowAtIndexPath:)可以轻松实现。

(我在这里假设您确实希望每个单元格具有不同的高度。从您的问题来看,这是否有点混乱。如果您希望它们都是同样,只需在数据输入时设置rowHeight一次。)