hitlad hitlad - 23 days ago 5
iOS Question

How to avoid image size changes in UIImageView of UITableViewController in Swift

I am using a UITableViewController to display rows of playing cards. I've set the Mode to "Aspect Fit" and I've checked the "Clip Subviews" in the Storyboard for the ImageView in each row's cell, its ContentView parent, and the Cell that contains the ContentView.

Everything looks as expected when the table is initially displayed but, when I swipe to scroll through the table, some (not all) of the new rows that scroll into view have images scaled to the wrong size, as shown.

Images in some rows end up smaller than expected

It seems like if I drag quickly, I get more rows that are of the wrong size. If I drag slowly, all the new rows are scaled appropriately. When I use a different emulator, the incorrect scaling would make some of the images too big rather than too small and so the entire row of cards would not fit within the display.

Some rows have images too big to fit

In the code, I've set the contentMode and clipToBounds, but they do not seem to help:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("LineCell", forIndexPath: indexPath)

let index = indexPath.row % 4
let imagename = "cards\(index)"
let im = UIImage(named: imagename)

cell.contentMode = UIViewContentMode.ScaleAspectFit
cell.clipsToBounds = true
cell.contentView.contentMode = UIViewContentMode.ScaleAspectFit
cell.contentView.clipsToBounds = true
cell.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
cell.imageView?.clipsToBounds = true
cell.imageView?.image = im

return cell
}


Did I miss something obvious? Thanks!

Answer

I ended up using a programmatic way around the problem.

    let cellImage : UIImageView = UIImageView(frame: CGRectMake(0, 0, cell.bounds.size.width, cell.bounds.size.height))
    cellImage.contentMode = UIViewContentMode.ScaleAspectFit
    cellImage.clipsToBounds = true
    cellImage.image = im
    cell.addSubview(cellImage)

I would still like to find a way to do it via the Storyboard, which I recall used to work in a straightforward manner...back before Apple started coming out with devices of all shapes and sizes leading to their need to offer increasingly complicated ways to accommodate all the sizes in a semi-automated, constraint-based system that requires quite a bit of overhead even for the simplest tasks. But, for now, this will do.

Comments