简体   繁体   English

如何根据动态图像URL的高度来调整包含在UITableview的自定义单元格中的UIImageview的大小?

[英]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. 我在一个单独的xib文件中的一个自定义UITableviewcell中有一个UIImageview和一些其他组件,然后将其加载到UITable子类中的UITableview中,并从URL动态分配图像。

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. 现在的问题是,我想根据从URL获得的图像大小动态调整UIImageview和Tableview行的高度。 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. 它的工作原理很吸引人,但是问题是,这将减慢UITableview的滚动事件,当我尝试异步下载图像并更新主线程中的视图时,它不起作用。

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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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