我想在 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 使用剪辑 subview 。
问题是当我开始添加照片时,表格的滚动非常滞后:( 即使我删除了单元格的高度计算,也没有任何改变。
有没有人知道如何在 Swift 中让它变得流畅?
最佳答案
首先,您永远不应该在创建表格单元格的过程中更改行高。 UITableView
的行高更改非常昂贵。您应该使用 UITableViewDelegate
方法 tableView(heightForRowAtIndexPath:)
来告诉 TableView 每个单元格的高度应该是多少。这几乎肯定是您的主要问题。
一个较小的问题是从数据创建一个 UIImage
有点昂贵,而且您不断地创建新图像然后丢弃它们。
这两个问题的解决方案都很简单。一次创建所有图像并将它们放入模型中。然后 tableView(cellForWRowAtIndexPath:)
可以将已经创建的图像分配给 imageview,而 tableView(heightForRowAtIndexPath:)
实现起来很简单。
(我在这里假设您实际上希望每个单元格具有不同的高度。您的问题是否是这种情况有点令人困惑。如果您希望它们都相同,只需设置 rowHeight
当你的数据进来时。)
关于ios - swift UITableView 滞后于图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27622173/