Change height of UIImageview dynamically
Since you're using auto-layout constraints you need to update height constraint not image view frame. So connect your height constraint as an IBOutlet
heightConstraint
in your tableViewCell. And then in table view cellForRowAt
you have to set cell.heightConstraint.constant = image_height
. And this will give you the desired result.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// don't forget to dequeue your table view cell here
//change height of UIImageView
let image_height = image_width * CGFloat(viewModel.imageScale)
cell.heightConstraint.constant = image_height
//load image
_ = homeViewCell.mainImageView.af_setImage(withURL: URL(string: serverURL + viewModel.mainImage)!, placeholderImage: UIImage(named : "home_placeholder") ...
}
Dynamic size of UIImageView inside UITableViewCell
The problem was that I was downloading the images from the web when the cells were being initiated and again when they were being reused.
Donwloading the cells content only once and storing them solved the problem.
Another way could be calculating the cell content height and defining them at heightForRowAt indexPath
.
Swift - Dynamic UITableViewCell size based on image aspect ratio
For achieve this I use first a dictionary [Int:CGFloat]
to keep the calculated heigths of cells then in the heightForRowAtIndexpath
method use the values keeped in your dictionary, in your cellForRowAtIndexpath
method you should download your image, calculate the aspect ratio, multiply your cell width or your image width by your aspect ratio and put the height calculated in correspondent IndexPath number in your dictionary
In code something like this, this is an example of code using alamofire to load the images
var rowHeights:[Int:CGFloat] = [:] //declaration of Dictionary
//My heightForRowAtIndexPath method
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if let height = self.rowHeights[indexPath.row]{
return height
}else{
return defaultHeight
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "ImageCell") as? ImageCell
{
let urlImage = Foundation.URL(string: "http://imageurl")
cell.articleImage.af_setImage(withURL: urlImage, placeholderImage: self.placeholderImage, filter: nil, imageTransition: .crossDissolve(0.3), completion: { (response) in
if let image = response.result.value{
DispatchQueue.main.async {
let aspectRatio = (image! as UIImage).size.height/(image! as UIImage).size.width
cell.articleImage.image = image
let imageHeight = self.view.frame.width*aspectRatio
tableView.beginUpdates()
self.rowHeights[indexPath.row] = imageHeight
tableView.endUpdates()
}
}
})
}
I hope this helps
Constraining UIImageView height to respect dynamic UILabel height in UITableViewCell
Try setting thumbnail
vertical compression resistance
lower than title
vertical hugging priority
. In code it'll look like this:
thumbnail.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
titleLabel.setContentHuggingPriority(.required, for: .vertical)
Set height for UIImageView in UITableViewCell using height / width values
What you need to do is deactivate your height constraint each time the cell is reused. Also, you need to set the height constraint equal to a multiple of the contentImageView
width constraint, not the cell's width constraint. So your code should look something like this:
final class ContentArticleImage: UITableViewCell {
var heightConstraint: NSLayoutConstraint?
var ratio: CGFloat? { // 1000 / 600 (width / height)
didSet {
guard let ratio = ratio else { return }
heightConstraint?.isActive = false
heightConstraint = contentImageView.heightAnchor.constraint(equalTo: contentImageView.widthAnchor, multiplier: 1 / ratio)
heightConstraint?.isActive = true
heightConstraint?.priority = .defaultHigh
}
}
lazy var contentImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.backgroundColor = .darkGray
imageView.contentMode = .scaleAspectFit
return imageView
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
configureUI()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
configureUI()
}
}
Note that I'm setting the priority
to .defaultHight
just to silence a layout warning in the console.
How to display image in table view cell with dynamic height?
You can prevent this log by making priority of the imageView's bottom constraint to 999 , as when cell loads it suggests a static height that conflicts with your constraints that always happens in dynamic tableViews
Related Topics
Getting Video Snapshot for Thumbnail
Ios5 What Does "Discarding Message for Event 0 Because of Too Many Unprocessed Messages" Mean
How to Check Whether Dark Mode Is Enabled in iOS/Ipados
How to Select Range of Values When Using Arc4Random()
Xcframework with Pods Dependencies
Xcode 7.1 Swift 2 Unknown Class in Interface Builder File
Uialertcontroller Text Alignment
Resize Mkannotationview Image When Map Zooms in and Out
How to Animate a Uibutton Between Two Png Images
Connect to Vpn Programmatically in iOS 8
Change the Font Size of Uisearchbar
Swiftui: Unwanted Split View on iPad
Uiview. Why Does a Subviews Outside Its Parent's Extent Not Receive Touches
Adding Glow Effect to Uibutton - iOS
Crashlytics iOS - Log Caught Exception
Nslocalizedstring Only Retrieves the Key, Not the Value in Localizable.Strings (Ios)