I have a tableViewCell which contains a ImageView.The image of the ImageView is download from a URL,so the height of every image is various.
So I use this code below to change the height of ImageView to display the image with different height:
In tableViewCell class :
let imageUrl = URL(string :"My url dynamic from API which different for every cell")
if let data = try? Data(contentsOf: imageUrl!)
{
guard let actualImage: UIImage = UIImage(data: data) else{
//do other thing here
}
let imageHeight = actualImage.size.height * actualImage.scale
defaultItemImageHeightContrainst = ItemImageHeightContrainst.constant
itemImageHeightContrainst.constant = imageHeight
itemImageView.translatesAutoresizingMaskIntoConstraints = false
layoutIfNeeded()
//kingfisher
itemImageView.kf.setImage(with: imageUrl)
}
By using the code above I can change the height of ImageView dynamically but the value of imageHeight(as declare above) is always 816,2520(This is extremely high),which produce the output below:
As you can see,it left a lot of blank space since the Image is not that tall.Cause I want my Image is in Aspect Fit mode.
After all the searching,I use this code below from this answer to set width and height of imageView in tableViewCell.This can reduce the blank space if the imageView,but it also cause the tableView very lag when I scroll the tableView
New approach to resize the imageView
func imageSizeAspectFit(imgview: UIImageView ,image : UIImage) -> CGRect {
var newwidth: CGFloat
var newheight: CGFloat
//let image: UIImage = imgFeed.image!
if image.size.height >= image.size.width {
newheight = imgview.frame.size.height;
newwidth = (image.size.width / image.size.height) * newheight
if newwidth > imgview.frame.size.width {
let diff: CGFloat = imgview.frame.size.width - newwidth
newheight = newheight + diff / newheight * newheight
newwidth = imgview.frame.size.width
}
}
else {
newwidth = imgview.frame.size.width
newheight = (image.size.height / image.size.width) * newwidth
if newheight > imgview.frame.size.height {
let diff: CGFloat = imgview.frame.size.height - newheight
newwidth = newwidth + diff / newwidth * newwidth
newheight = imgview.frame.size.height
}
}
print(newwidth, newheight)
//adapt UIImageView size to image size
let screenSize: CGRect = UIScreen.main.bounds
return CGRect(x: 0, y: 0,width: screenSize.width, height: newheight)
}
So my question is :
1) What is the correct way to change the height of a ImageView with AspectFit mode according to the actual height of the image that download from a
URL ?
2) If the code in New approach to resize the imageView section above is the correct way then how to make the tableView not lag when scrolling?
