简体   繁体   中英

How to resize an UIImageview, enclosed within a UITableview's custom cell, depending upon dynamic image URL's height?

I'm having a UIImageview and few other components within a custom UITableviewcell, in a separate xib file, which I'm loading into my UITableview, which is in a UIView subclass and assigning image from URL dynamically.

Now the problem is, I want to resize the UIImageview and the Tableview row's height depending upon the size of image, obtained from the URL, dynamically. I got that working using the following code,

    if  let bpImageUrls = singleComponent["picture_link"]{
        cell.newsImage.sd_setShowActivityIndicatorView(true)
        cell.newsImage.sd_setIndicatorStyle(.gray)
        cell.newsImage.sd_setImage(with: URL(string: bpImageUrls as! String))

        let imageData =  NSData(contentsOf:URL(string: bpImageUrls as! String)!)

        let myImage = UIImage(data: imageData! as Data)
        let aspectRatio = ( myImage?.size.height)! / ( myImage?.size.width)!

        cell.imageHeightConstraint.constant = UIScreen.main.bounds.size.width * aspectRatio
    }

It works like a charm, but the problem is, this will slow down the scrolling event of the UITableview, when I tried to do download the image asynchronously and update the view in the main thread, it's not working.

The view is tied with autolayout like in this image , I'd been struggling with this for a while now. Any insights will be helpful. Thanks.

When you load the image asynchronously the table view has already finished the layout for the cell. Just changing the cell's height constraint according to the image height does not change the height of the cell in the table view.

You have to make the table view recalculate the height of the cell after changing the height constraint. So when an image is loaded and the height constraint of the cell changed, tell the table view to reload that cell by calling:

if let indexPath = tableView.indexPath(for: cellWithImage) {
    tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM