I had this same exact issue not long ago.
First, you should set image content mode to Aspect Fit, BUT it is not enough.
You will have to change imageView's aspect ratio constraint every time you want to load a new image. Basically, what you need to do is:
let aspectRatio = Float(image.height) / Float(image.width)
This is a copy-paste (with added comments) of my code where I managed this issue. Hope it will help you.
// aspectRatioCnst is IBOutlet reference to aspect ratio constraint I've set on mainImageView in Storyboard
if let aspectRatioCnst = aspectRatioCnst {
aspectRatioCnst.isActive = false
}
let aspectRatio = Float(imagePost.height) / Float(imagePost.width)
aspectRatioCnst = NSLayoutConstraint(
item: self.mainImageView,
attribute: NSLayoutAttribute.height,
relatedBy: NSLayoutRelation.equal,
toItem: self.mainImageView,
attribute: NSLayoutAttribute.width,
multiplier: CGFloat(aspectRatio),
constant: 0)
if let aspectRatioCnst = aspectRatioCnst {
self.mainImageView.addConstraint(aspectRatioCnst)
aspectRatioCnst.isActive = true
self.mainImageView.layoutIfNeeded()
}
if let image = imagePost.loadedImage {
self.mainImageView.image = image
} else if let imageURL = URL(string: imagePost.fileURL) {
DispatchQueue.global(qos: .background).async {
// UIImage extension with downloadedFromURL method
UIImage.downloadedFromURL(url: imageURL, withCallback: { (image) -> (Void) in
DispatchQueue.main.async {
self.imageLoadingActivityIndicator.stopAnimating()
self.mainImageView.image = image
self.imagePost?.loadedImage = image
}
})
}
}
First set your bottom content a height like this,
Then set your image constrains like this,
Then do this in your code,
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let imageNew = UIImage(named: "test") //Set your image here
let oldWidth = imageNew!.size.width
let scaleFactor = tableView.frame.size.width / oldWidth
let newHeight = imageNew!.size.height * scaleFactor
let newWidth = oldWidth * scaleFactor
//Finally to get cell size just add the bottom part height for othercontents to ImageHeight here
let CellSize = CGSize(width: newWidth, height: (newHeight + 40))
return CellSize.height
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell
cell.NewImage.image = UIImage(named: "test")
return cell
}
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.