I would like to show images in TableView so I created a custom cell
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
}
I had a problem how to adjust cell's height so for each image its calculated separately and I use clip subviews for ImageView.
The problem is that when I start adding photos the scroll of table is very laggy :( Even when I remove cell's height calculation nothing's changed.
Does Anyone has any idea how to make it smooth in Swift?
First, you should never change row heights in the middle of creating table cells. Row height changes are very expensive for UITableView
. You should use the UITableViewDelegate
method tableView(heightForRowAtIndexPath:)
to tell the table view what each cell height should be. This is almost certainly your major problem.
A lesser problem is that creating a UIImage
from data is somewhat expensive, and you keep creating new images and and then throwing them away.
The solution to both of these is simple. Create all your images once and put them in your model. Then tableView(cellForWRowAtIndexPath:)
can just assign the already-created image to the imageview, and tableView(heightForRowAtIndexPath:)
is trivial to implement.
(I'm assuming here that you actually want each cell to have a different height. It's a little confusing from your question whether that's the case. If you want them all to be the same, just set rowHeight
once when your data comes in.)